Compare if two variables reference the same object in python

后端 未结 6 1182
别跟我提以往
别跟我提以往 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:30

    While the two correct solutions x is z and id(x) == id(z) have already been posted, I want to point out an implementation detail of python. Python stores integers as objects, as an optimization it generates a bunch of small integers at its start (-5 to 256) and points EVERY variable holding an integer with a small value to these preinitialized objects. More Info

    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 implementation detail), 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
    

提交回复
热议问题