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?

2
  • 1
    Does this answer your question? "is" operator behaves unexpectedly with integers Commented Mar 28, 2020 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. Commented Mar 28, 2020 at 23:16

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. I'm still finding this pretty confusing but I'll get the hang of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.