简体   繁体   中英

tuple vs list objects in 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?

is is based on object identity. IE, 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM