Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tuple vs list objects in python

Tags:

python

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?

like image 348
jachym Avatar asked Nov 11 '10 19:11

jachym


3 Answers

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.

like image 67
Matthew Flaschen Avatar answered Sep 21 '22 19:09

Matthew Flaschen


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
like image 42
John La Rooy Avatar answered Sep 19 '22 19:09

John La Rooy


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).

like image 23
Russell Borogove Avatar answered Sep 23 '22 19:09

Russell Borogove