+ 4
Why print([] is []) is false?
why does two empty lists are not equal as in case print("p" is "p") returns true ..
1 Resposta
+ 3
The is operator checks the identities (i.e., memory locations) of the objects (id()) and returns True if id(obj1) == id(obj2). Otherwise, it returns False.
Whenever python sees "[]", it creates a new empty list. So when it sees "[] is []", it creates two new empty lists, with different id values, compares their id values, finds that they're different, and returns False.
However, if we do
id([])
4330636208
id([])
4330636208
Huh? It put them both in the same place! So [] is [] should find matching identities and return True, right?
Well..., no. What happens is that "id([])" creates a new, empty list, retrieves its id/location, and prints that out, then, since there's nothing referencing that new list, it gets garbage collected. By the time I get around to typing "id([])" the second time, the space the first list occupied has been freed up and is available to be used for the second list, so the second list winds up at the same location as the first one.
So why doesn't that happen when we print the value of "[] is []"?
Because python has to hold onto the first empty list until it does the comparison. Because the first list has a reference that lives as long as the comparison, it doesn't get garbage collected until after the second list is created and the comparison is completed. That forces the second empty list to be created in a new location so their id values are different and the "is" evaluates to False.
The same thing happens with other non-scalar empties like {} (empty dictionary) and set([]) (empty set).
However None is None evaluates to True.