Compare if two variables reference the same object in python

How to check if two variables refer to 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 
+83
python
Mar 26 '11 at 20:27
source share
6 answers

This is what is : x is y returns True if x and y are the same object.

+116
Mar 26 '11 at 20:29
source share

y is x will be True , y is z will be False .

+12
Mar 26 '11 at 20:29
source share

While the two correct solutions are x is z and id(x) == id(z) I want to point out the details of the python implementation. Python stores integers as objects, as an optimization, it generates a bunch of small integers at the beginning (-5 - 256) and points to EVERY variable containing an integer with a small value, these pre-initialized objects. More information

This means that for integer objects initialized with the same small numbers (from -5 to 256), checking if the two objects are the same will return true (ON C-Pyhon, as far as I know, this is an implementation detail), while for a larger number returns true only if one object is initialized from another.

 > i = 13 > j = 13 > i is j True > a = 280 > b = 280 > a is b False > a = b > a 280 > a is b True 
+8
Jan 28 '16 at 14:11
source share

You can also use id () to check which unique object each variable name refers to.

 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) 
+7
Dec 13 '15 at 3:14
source share

I really enjoy having visual feedback, so sometimes I just open http://www.pythontutor.com/visualize.html#mode=edit to see how memory is allocated and what refers to what.

enter image description here

Added this awesome gif as this answer is about visualization.

+1
Dec 09 '17 at 8:05
source share

This is from docs.python.org: "Each object has an identity, type, and value. An object’s identity never changes after it is created; you can think of it as the address of objects in memory. The is operator compares the identity of two objects; the id () function returns an integer representing its identity. "

Apparently, every time you change the value, the object is recreated, as shown by a change in identity. Line x = 3, followed by line x = 3.14, gives no errors and gives various identifiers, types and values ​​for x.

+1
Mar 26 '18 at 22:48
source share



All Articles