3
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?

inspd
  • 145
  • 3

2 Answers2

4

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
Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • why don't `b` and `a` have the same location in memory when both assigned to `[2]` ? aren't they pointing to the same object ? excuse my limited knowledge – inspd May 07 '16 at 04:09
  • *why don't b and a have the same location in memory when both assigned to `[2]` ?* This is because every time you write `[2]` you create a *new* array. You aren't reusing an existing array. – Michael Geary May 07 '16 at 04:31
0

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
tknickman
  • 4,285
  • 3
  • 34
  • 47