Reputation: 117
Why does the code below produce:
False
False
False
and not: False True False
def foo(el):
return (el is 0.0)
seq=[0,0.0,False]
for el in seq:
print( foo(el) )
Upvotes: 1
Views: 369
Reputation: 71689
The is
keyword in python is used to test if two variables refer to the same object. It returns True
if the two variable are referring to same object otherwise it returns False
.
For Example consider the class
named A
:
class A:
pass
Case 1:
x = A() #--> create instance of class A
y = A() #--> create instance of class A
>>> x is y
>>> False
Case 2:
x = A() #--> create instance of class A
y = x #--> here y refers to the instance of x
>>> x is y
>>> True
Basically two variables refer to same object if they are referring to same memory location. You can check the identities of the variable by using the built in function in python called id()
, this function returns the identity of the object (address of the object in memory).
id(x)
is not equal to id(y)
hence x is y
returns
False
. id(x)
is equal to id(y)
which implies both x
and y
refers to the same object inside the memory hence x is y
returns
True
.Now coming to your question,
def foo(el):
return (el is 0.0)
In the function foo
el is 0.0
returns False
because each of the two entities el
and 0.0
refer to different locations inside memory. You can verify this fact by comparing id(el) == id(0.0)
which returns False
.
Upvotes: 2