I'm trying next code:
x = 'asd'
y = 'asd'
z = input() #write here string 'asd'. For Python 2.x use raw_input()
x == y # True.
x is y # True.
x == z # True.
x is z # False.
Why we have false in last expression?
I'm trying next code:
x = 'asd'
y = 'asd'
z = input() #write here string 'asd'. For Python 2.x use raw_input()
x == y # True.
x is y # True.
x == z # True.
x is z # False.
Why we have false in last expression?
is
checks for identity. a is b
is True
iff a
and b
are the same object (they are both stored in the same memory address).
==
checks for equality, which is usually defined by the magic method __eq__
- i.e., a == b
is True
if a.__eq__(b)
is True
.
In your case specifically, Python optimizes the two hardcoded strings into the same object (since strings are immutable, there's no danger in that). Since input()
will create a string at runtime, it can't do that optimization, so a new string object is created.
is
checks not if the object are equal, but if the objects are actually the same object. Since input()
always creates a new string, it never is
another string.
Python creates one object for all occurrences of the same string literal, that's why x
and y
point to the same object.