+ 1
In python why 'is' cmd returns different values for below scenarios?
If a,b=[0],[0] ,when user performs 'a is b' returns False.But when user does a,b=0,0 and performs 'a is b' returns 'True'
3 Réponses
+ 4
The memory id's are different.
'''
a,b=[0],[0] #creates 2 separate lists
print(id(a), id(b))
a,b=0,0 #a=0 & b=0
print(id(a), id(b))
'''
Lists can have the same values, but different places in memory. However when variables are created and then given a specific value, a place in memory is created. If another variable with the same value is created, the place in memory is assigned to that variable. Lists behave differently and each list is given a different place in memory. The "is" operator is comparing memory location, hence,the id() method, which finds the objects memory location
+ 3
'is' checks if they are pointing at the same object. if you did a = b and did a is b it would return true.
if you need to compare values you should use ==
+ 1
[meta, in support of other answers only]
# print id's
a,b=[0],[0]
print(id(a), id(b), id(a[0]), id(b[0]), id(0), sep="\n")
16795048 # a, the list
16796208 # b, the list
1876965616 # a[0], having the value 0
1876965616 # b[0], having the value 0
1876965616 # 0, the value
Perplexed? In Python, even numbers are objects:
print(dir(0))
['__abs__', '__add__', ... ]