Shafin M
Shafin M

Reputation: 91

Confusion about Python operator 'is'

Python console snapshot

Definition of 'is' operator in python:

is operator checks whether both the operands refer to the same object or not

Then how come when the id of a and list1[0] don't match, the 2nd condition is True?

Upvotes: 1

Views: 38

Answers (1)

rdas
rdas

Reputation: 21275

What you're doing when you're doing id(a) is id(list1[0]) is comparing the values returned by the id() function to check if they point to the same object or not. Those values are different objects - EVEN IF THEY ARE THE SAME VALUE

Check this:

a = 2
ll = [2]

print(a is ll[0])
print(id(a), id(ll[0]))
print(id(a) is id(ll[0]))

Which gives:

True
140707131548528 140707131548528
False

Now why is the first result True? Because of interning - all ints between -5 & 256 are pre-created objects that are reused. So every 2 in python is actually the same object. But every 140707131548528 is different

Upvotes: 4

Related Questions