Some immutable objects are cached in python, being some numbers and strings an example. That means, when you write 1
you get a reference to an object that already existed on the heap.
Lists are not cached (makes little sense, starting from the fact that they are mutable), and therefore they have different identity, although they can be equal in contents.
Maybe a little comparison helps. Each person that takes a look at the moon, is seeing the very same moon (that would be getting a reference to 1
)... therefore you can say that
id(my_moon) == id(your_moon)
or just
my_moon is your_moon
Since the moon is the moon, and 1
is 1
, some implementations of python decide to cache this object for performance reasons.
On the other hand, mutable objects are a horrible candidate for caching. For instance, each person that takes a bag of chips, is taking a different instance of a bag of chips, therefore it can be that at some point
my_chips == your_chips
because they have the same amount of chips, but in no case whatsoever it would be
id(my_chips) == id(your_chips)
because that would mean that the object is shared, and when somebody else eats a chip (mutates the chips bag object), a chip would dissapear from your bag... and that would be a terrible world to live in :)