Compare if two variables reference the same object in python

后端 未结 6 1181
别跟我提以往
别跟我提以往 2021-01-30 06:29

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         


        
6条回答
  •  醉话见心
    2021-01-30 06:46

    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)
    

提交回复
热议问题