a = 2
b = 2
print(b is a)
a = [2]
b = [2]
print(b is a)
The first print returns True and the second print returns False. Why is that?
a = 2
b = 2
print(b is a)
a = [2]
b = [2]
print(b is a)
The first print returns True and the second print returns False. Why is that?
 
    
    In Python small ints are memoized to be more efficient.
So, b is a is True because they have the same location in memory.
is checks for object identity. If you want to check for equality use == except for None in which case there seems to be a general consensus to use is
>>> a = 2
>>> b = 2
>>> id(a)
1835382448
>>> id(b)
1835382448
 
    
    is checks for object identity (is list a the same instance as list b). And == compares value identity (is what is stored at the variable a equivalent to what is stored at the variable b)
So in your case. [2] is the value, and while variable a and variable b both store the this value, they are not the same (you could modify a, and b would not change)
If you added another variable and pointed it to a, you could see this behavior:
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [2]
>>> b = [2]
>>> a == b
True
>>> a is b
False
>>> c = a
>>> c == a
True
>>> c is a
True
