1

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) )

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
david
  • 117
  • 1
  • 5

1 Answers1

2

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).

  • In Case 1 id(x) is not equal to id(y) hence x is y returns False.
  • In Case 2 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.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
  • Ok thanks! Why is the 0.0 the only element where the id is different? If the return statement was --> return (el is 0) or return (el is False), you get True – david Apr 01 '20 at 16:59
  • 1
    Thats because of the internal implementation of python which states **two objects with non-overlapping lifetimes may have the same id() value.** Eg. if you declare two variable `a = 2` and `b = 2` then in that case `id(a) == id(b)` will return true. but when you declare two variables `a = 2.5` and `b = 2.5` then `id(a) == id(b)` returns `False` because python compiles them as two different object, its totally based on the internal implementation in python. For more details about the behaviour of floats in python refer to this [post](https://stackoverflow.com/a/38835030/12833166) . – Shubham Sharma Apr 01 '20 at 17:16