The following makes sense to me:
>>> [] is []
False
Given that lists are mutable, I would expect []
to be a new empty list object every time it appears in an expression. Using this explanation however, the following surprises me:
id([]) == id([])
True
Why? What is the explanation?
In the first example,
[]
is not[]
precisely because the lists are mutable. If they weren't, they could safely map to the same one without issue.In the second example,
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 nilFrom the docs on id:
Commented disassembly:
Note there is no
STORE_FAST
to retain the list. Therefore it was discarded immediately after getting passed to theid
function.