0

is operator : I know that is operator checks whether both the operands refer to the same object or not.

a = "Hello World!"
b = a

print(a == b)
print(a is b)

output

True
True

Now, I will use input() to get input from the user.

c = "Python"
d = input("Enter string : ")

print(c == d)

output

Enter string : Python
True

but if I will try to print

print(c is d)

output

False

I don't know why it is happening with input().

If I directly assign one variable to another variable, is operator is working fine but if I will get same value from input(), is opeartor will be given False.

I want to know that, why it is not referring the same object when we use input().

MK Patel
  • 1,354
  • 1
  • 7
  • 18
  • Why do you *think* they *should* be same object? – juanpa.arrivillaga Feb 25 '20 at 13:09
  • because if we write `a="Hello" b="Hello"` then it will refer same object. So, if we will get the value of b as "Hello" from input() then also it should be refer to the same object as per my thoughts. – MK Patel Feb 25 '20 at 13:12
  • 2
    That totally depends on implementation details, like string literals in code blocks being optimized to be the same object, but there's no reason to believe that they should be, and knowing when the compiler decides that isn't straightforward. Note, it is **always** the case that `a = b` will mean `a is b`, but just because two objects are *equal* does not mean they will be *identical*. Just because the compiler does optimizations underneath the hood doesn't imply it always will, and you shouldn't rely on that behavior anyway, because it is an implementation detail. – juanpa.arrivillaga Feb 25 '20 at 13:17
  • 1
    IOW you shouldn't be surprised that `print(c is d)` is False, what *should* surprise you is that `a="Hello"; b="Hello"; print(a is b)` is *true*. – juanpa.arrivillaga Feb 25 '20 at 13:19
  • 1
    In IDLE you even get different results for `x is y` depending on if you write `x = y = 999` or `x = 999` and `y = 999` on two different lines. Then switch `999` with `23` and the result will be different again. So as @juanpa.arrivillaga said: it's an implementation detail. – Matthias Feb 25 '20 at 13:28
  • @Matthias to be clear, if you do `x = y = ` then `x is y` will *always be true*. Same with `x = ` then `y = x` – juanpa.arrivillaga Feb 25 '20 at 13:42

0 Answers0