5

Can someone explain me this?

>>> [] is []
False
>>> () is ()
True
>>> (1,) is (1,)
False

I understand that I should use "==" instead of "is"to compare the values, I am just wondering why it is this way?

3 Answers 3

10

is is based on object identity. I.E., are the left and right the same object?

In all these cases, the objects would ordinarily be different (since you have six separate literals). However, the empty tuples are the same object due to implementation-dependent interning. As you noted, you should never rely on this behavior.

Note that mutable objects can not be interned, which means the first must be false.

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

2 Comments

Note, "interning" can (usually does) apply to strings, as well as any other immutable literal/value. Because they are immutable any implementation of Python has the option to make different references converge (point to) any single instance of the object. That's what interning means in this context. Interning is an implementation detail which optimizes for common use cases. Python lists, by the way, are mutable and thus cannot be subject to interning.
The first is not a comparison between a list and a tuple, but between two lists. It's false because they are different objects (i.e., different ids) which only happen to have the same value (i.e., both are empty lists).
3

Be careful when comparing by id. If an object is GC'd the id can be reused!

>>> id([])==id([])
True

or even

>>> id([1,2,3])==id(["A","B","C"])
True

Comments

2

Think of it this way: In your first case, for immutable objects like tuples, it's safe for the python implementation to share them if they're identical:

>>> a = ()
>>> b = ()
>>> a is b
True

Now consider:

>>> a = []
>>> b = []
>>> a.append("foo")
>>> print a,b
['foo'] []

It's not possible for a and b to be the same object, because modifying a shouldn't modify b.

In your final example, you're back to immutable tuples. The Python implementation is allowed to make them the same object, but isn't required to, and in this case it doesn't (it's basically a space/time tradeoff - if you used a lot of (1,) in your program you could save memory if they were interned, but it would cost runtime to determine if any given tuple was a (1,) that could share the object).

Comments

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.