0

I'm starting a basic online course of Python and I was wondering why when I use is when comparing two same float values is results as False.

I've been trying these combinations:

# C1
x = 3
y = 3.0
x is y # False
# C2
x = 3.0
y = 3
x is y # False

I know if I use == it appears true for the second combination because it is comparing values.

I was thinking it would appear for

x = 3.0
y = 3.0
x is y # True

because it points to the same object, but instead, it appears as False. Do you know why?

Thanks for your answers!

7
  • because it points to the same object No they do not. x and y have the same value, but they are separate objects. The is operator tests if two names point to the same object. Commented Mar 23, 2024 at 23:54
  • 4
    is has absolutely nothing to do with values - the only thing it tells you is whether the left and right operands are the same object. An int and a float are certainly never going to be the same object. Two floats with the same value may be the same object, or they may be different objects; there's no guarantee one way or the other, nor is there any particular reason for you to care. Commented Mar 23, 2024 at 23:57
  • Consider for a moment what it would require to do what you are thinking. If would require Python to go through the list of all objects to figure out if 3.0 was already in an object somewhere. Now, Python actually DOES that for small integers, but certainly not for floats. Commented Mar 24, 2024 at 0:10
  • There are two completely separate questions here, about is and about ==. Both are well covered by existing separate Q&A. Commented Mar 24, 2024 at 0:44
  • @tdelaney "The only defined singletons out there are None, True and False" - And Ellipsis and NotImplemented (and I'm not sure there aren't even more...). Commented Mar 24, 2024 at 2:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.