0
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?

Community
  • 1
  • 1
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • 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 Jun 13 '14 at 03:03

2 Answers2

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
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76