print id ([]) == id([])
>>> True
Why? Because:
id([]) creates a list, gets the id, and deallocates the list. The second time around it creates a list again, but "puts it in the same place" because nothing much else has happened. id is only valid during an object's lifetime, and in this case its lifetime is virtually nil
So whats the difference here?
print id ({}) == id([])
>>> False
Shouldn't it be creates a dict, gets the id and dealocates the dict, then create a list puts it in the same because nothing much else has changed?
-
Where things get allocated is an implementation detail. We can explain why things happen this way, but don't rely on them happening this way, because they might happen differently without warning if the implementation changes.user2357112– user23571122014年06月13日 03:03:39 +00:00Commented Jun 13, 2014 at 3:03
2 Answers 2
Lists and dicts are not stored in the same memory areas, so they get different IDs from each other. Two arrays created and deallocated right after each other will get the same IDs, and so will two dicts, but the dicts won't get the same IDs as the arrays.
>>> print id([])
3073720876
>>> print id([])
3073720876
>>> print id({})
3073762412
>>> print id({})
3073762412
Comments
You've hit the nail on the head. It creates a dict. The latter creates a list, explaining this behavior:
>>> [] == {}
False
>>> id([]) == id({})
False
>>>
>>> id([])
4301980664
>>> id({})
4298601328
>>>
Lists and dicts are not stored in the same way, so two different types will not return the same thing. However, two lists or two dicts will return the same.