-1

If I do the following

x = 0
y = 0
print(x is y)

I get True

The following code

x = 0
y = 0.0
print(x is y)

outputs False which is the expected behavior.

But

x = 0.0
y = 0.0
print(x is y)

returns False. Why does this happen and how to get around it?

My use case is that I need to distinguish 0 and 0.0 from other values in python like False, "", etc which would return True in a x==0 comparison

EDIT:

The linked question in the comments does not answer my question. I need to know how to get around this problem.

Guy
  • 604
  • 5
  • 21
  • does this answer your question? https://stackoverflow.com/questions/38834770/is-operator-behaves-unexpectedly-with-floats – Anurag Wagh Jun 22 '20 at 04:58
  • 2
    Does this answer your question? ['is' operator behaves unexpectedly with floats](https://stackoverflow.com/questions/38834770/is-operator-behaves-unexpectedly-with-floats) – Anurag Wagh Jun 22 '20 at 04:59
  • yeah, [check this answer](https://stackoverflow.com/a/38835030/11984670) – Tibebes. M Jun 22 '20 at 05:01
  • It only answers the first part of my question. I need a way to get around this issue. – Guy Jun 22 '20 at 05:04

1 Answers1

1

You can check the type first and then the values in that case.

Something like this:

>>> a = 0
>>> b = 0
>>> c = 0.0
>>> d = 0.0
>>> type(a) is type(b) and a == b
True
>>> type(a) is type(c) and a == c
False
>>> type(c) is type(d) and c == d
True
>>>
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36