I know when Python handles object, it uses ‘reference’ to the object, not the real value itself.
But behavior of below code seems very odd to me.
5 dummy object references were copied from
now list, then
prev was cleared.
Then, shouldn’t references stored in
now be invalidated too?
class dummy: pass prev = [dummy() for _ in range(5)] now =  for d in prev: now.append(d) for idx in range(5): print(prev[idx] is now[idx]) # all True - so, same reference copied prev.clear() print(prev) # empty print(now) # 5 'dummy' objects survived - How??
I found possible duplicate to this question, and would like to ask if this is the reason why references in
now isn’t invalidated after
Python: Delete object referenced from tuple
Maybe I’m too used to reference concept in C++ and Python is different.
By adding each object in
now, you increment their reference counts by 1, so they become 2.
When you delete the objects in
prev, reference count of each object is decremented by 1, and they become 1.
Since reference counts of the objects did not reach 0, they do not go away.