Compare if two variables reference the same object in python

How to check whether two variables reference the same object?

x = ['a', 'b', 'c']
y = x                 # x and y reference the same object
z = ['a', 'b', 'c']   # x and z reference different objects
64518 次浏览

这就是 is的作用。

在这个示例中,x is y返回 True,因为它是同一个对象,而 x is z返回 False,因为它是不同的对象(碰巧保存着相同的数据)。

y is xTrue y is zFalse

还可以使用 id()检查每个变量名所引用的唯一对象。

In [1]: x1, x2 = 'foo', 'foo'


In [2]: x1 == x2
Out[2]: True


In [3]: id(x1), id(x2)
Out[3]: (4509849040, 4509849040)


In [4]: x2 = 'foobar'[0:3]


In [5]: x2
Out[5]: 'foo'


In [6]: x1 == x2
Out[6]: True


In [7]: x1 is x2
Out[7]: False


In [8]: id(x1), id(x2)
Out[8]: (4509849040, 4526514944)

虽然已经发布了两个正确的解决方案 x is zid(x) == id(z),但是我想指出 python 的实现细节。Python 将整数存储为对象,作为一种优化,它在开始时(-5到256)生成一堆小整数,并将每个保存一个小值整数的变量指向这些预先初始化的对象。更多信息

This means that for integer objects initialized to the same small numbers (-5 to 256) checking if two objects are the same will return true (ON C-Pyhon , as far as I am aware this is an 实施细节), while for larger numbers this only returns true if one object is initialized form the other.

> i = 13
> j = 13
> i is j
True


> a = 280
> b = 280
> a is b
False


> a = b
> a
280
> a is b
True

我真的很喜欢有一个视觉反馈,这就是为什么我有时只是打开 http://www.pythontutor.com/visualize.html#mode=edit,看看如何分配内存,什么是引用什么。

enter image description here

增加了这个令人敬畏的 gif,因为这个回复是关于可视化. 。

来自 docs.python.org: “每个对象都有一个标识、一个类型和一个值。对象的标识一旦创建就不会改变; 您可以将其视为对象在内存中的地址。‘ is’运算符比较两个对象的标识; id ()函数返回一个表示其标识的整数。”

显然,每次更改值时,都会按照标识更改所指示的方式重新创建对象。行 x = 3后面跟着行 x = 3.14没有错误 & 给出了 x 的不同的标识、类型和值。