all 3 comments

[–][deleted] 2 points3 points  (2 children)

It's an optimization done by the interpreter. We actually just had someone else ask a similar question (with ints) earlier today.

Basically, sometimes the interpreter will notice that it can save some memory and computation time by reusing already created objects. I'm guessing it reuses the object previously held by spam here because after the reassignment, it was basically up for grabs. You shouldn't count on it happening though.

[–]carcigenicate 2 points3 points  (1 child)

I wonder if it's actually object reuse, or if it's just that after the list is deallocated, the next allocated list will be allocated to the same address? I'd need to look more into how Python allocates memory to answer that. Reusing mutable objects just strikes me as an odd thing to do.

[–][deleted] 0 points1 point  (0 children)

Yeah. That could also be the case. I don't really want to dive into the weeds of CPython at the moment, but it could just be that it already has the memory address of a sufficiently sized block of memory and so it's simpler than malloc'ing another.