开发者

tuple vs list objects in python

开发者 https://www.devze.com 2023-01-24 09:48 出处:网络
Can someone explain me this? >>> [] is [] False >>> () is () True >>> (1,) is (1,)

Can someone explain me this?

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

I understand that I should use "==" instead of "开发者_如何学JAVAis"to compare the values, I am just wondering why it is this way?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消