3

num1 and num2 both are 3.5 and num1 == num2 gives True, but for is operator it is False.

Look at the below code,

Input:

num1 = 3.5
num2 = float(input('num2:'))  # num2 stands for 2nd number
print(num1 == num2)
print(num1 is num2)

Output:

num2:3.5
True
False

num1 and num2 both are 3.5 and num1 == num2 gives True, but for is operator it is False.

Why is id(num1) != id(num2) ?

Kaushik
  • 187
  • 3
  • 13
  • https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is – mattrea6 Sep 25 '19 at 14:50
  • 1
    Closed too quickly - it isn't a pure duplicate of that, though it is closely related. I was halfway through writing an answer about how integers and floats differ in python, which is why we get this behaviour with floating point values and not integers. – Baldrickk Sep 25 '19 at 14:57
  • @Baldrickk it is still a duplicate - the reason why it doesn't _always_ work the same for ints _in CPython_ is explained in the accepted answer of the dup. – bruno desthuilliers Sep 25 '19 at 15:04

3 Answers3

1

Briefly speaking, is will check for identity, while == will check for equality. The is operator compares the identity of two objects, while the == operator compares the values of two objects.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
  • Why is num1 and num2 referring different addresses if both are 3.5? – Kaushik Sep 25 '19 at 14:48
  • 1
    @Kaushik, I think that the fact you are using floats could the reason. I tried the same code with integers both variables return the same id. – lmiguelvargasf Sep 25 '19 at 14:50
  • Yes, even I tried it and it produced True for both. But why is it False for is when we use float? – Kaushik Sep 25 '19 at 14:52
  • 3
    @Kaushik the CPython implementation use internal caching on some immutable objects (notably small integers - for a definition of "small" that already changed a lot since the 1.5.x days - and literal strings that match python identifier syntax). __This is an implementation detail__. Nothing in the Python language definition mandates that this caching should or shouldn't happen, all it states is that `is` compares the ids of objects (_not_ their "memory location" - the fact that CPython uses memory address as id is also is an implementation detail). – bruno desthuilliers Sep 25 '19 at 14:57
1

The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not.

1

Like the other two said, == checks equality, is checks id(). Play around with id() to see what the object id's are, they won't be the same which is why 'is' comes back false.

gitdaze
  • 21
  • 3