'How the operator (is) works with tuples and lists [duplicate]
Why when I compare two equal tuples through the operator (is) I get a different result than when I compare two equal lists? (one is True an the other is False)
Nothing really... i am starting with python and i do not want to leave my doubts :)
a=(1,2,3)
b=(1,2,3)
c=[1,2,3]
d=[1,2,3]
print(a is b) #True
print(c is d) #false
I expected that both were False :(
Solution 1:[1]
Python may optimize small read-only objects (strings, numbers, tuples) by "interning" them (keeping a list of common small objects), or noticing they are the same at compile-time and not making a second copy.
Since these objects can not be changed, this is a safe optimization, and can result in is
returning True for two objects that would otherwise be separate.
The actual specifics are version specific and can change from release to release. They are certainly equals (==
) , but may or may not be the same (is
).
Lists can be modified (they are mutable
), therefore, under the current language rules, they have to be viewed as different objects. They have separate identify and are not is
the same. Otherwise changing c
would change d
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |