Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: what difference between 'is' and '=='? [duplicate]

Tags:

python

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?

like image 898
Ivan Zelenskyy Avatar asked Dec 05 '22 07:12

Ivan Zelenskyy


1 Answers

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.

like image 121
Amir Rachum Avatar answered Dec 08 '22 06:12

Amir Rachum