1

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?

Paolo
  • 21,270
  • 6
  • 38
  • 69
Shafin M
  • 91
  • 2
  • 11
  • 1
    Does this answer your question? ["is" operator behaves unexpectedly with integers](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers) – rassar Mar 28 '20 at 23:13
  • No I know about that case. Python keeps an array of integer objects for all integers between -5 and 256. When you create an integer in that range, you get back a reference to the already existing object. Anything outside of that creates a new reference. – Shafin M Mar 28 '20 at 23:16

1 Answers1

4

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

rdas
  • 20,604
  • 6
  • 33
  • 46