Why is this:
x = str(input("Enter a string: ")) #input "cat"
y = str(input("Enter another string: ")) #input "cat"
print(x is y) #Outputs False
Not the same as this:
x = "cat"
y = "cat"
print(x is y) #Outputs True
Why is this:
x = str(input("Enter a string: ")) #input "cat"
y = str(input("Enter another string: ")) #input "cat"
print(x is y) #Outputs False
Not the same as this:
x = "cat"
y = "cat"
print(x is y) #Outputs True
The is
operator in python is used to check if two objects point to the same memory location.
In the second case, when python runs, for optimization purposes both x and y point to the same memory location. However, in the first case, x and y are not defined until the user inputs a value during run time. So, they're both allocated memory in different locations.
From this Real Python article:
The
==
operator compares the value or equality of two objects, whereas the Pythonis
operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=, except when you’re comparing to None.
>>> x = None
>>> y = None
>>> id(x); id(y)
4389651888
4389651888
>>> x is y
True
==
calls the __eq__
method of an object, is
checks whether the id()
of two objects is equal (memory address).
The rest of the article I linked is really informative; it talks about how Python will give the same id to small integers by default, and that you can use the sys.intern()
method to ensure string variables point to the same object in memory as well.