inspd inspd - 6 months ago 19
Python Question

(Python) How is `2` different to `[2]` when using `is`?

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?

Answer

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
Comments