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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With