'is' vs '==' in python you must know it. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

'is' vs '==' in python you must know it.

# "is" vs "==" >>> a = [1, 2, 3] >>> b = a >>> a is b True >>> a == b True >>> c = list(a) >>> a == c True >>> a is c False # • "is" expressions evaluate to True if two # variables point to the same object # • "==" evaluates to True if the objects # referred to by the variables are equal

6th Mar 2018, 5:16 AM
Maninder $ingh
Maninder $ingh - avatar
1 Answer
0
This is an invariable rule of Python. It is correct for all same _basic_ types of data, even if you assign the value not by declaration but but calculation. >>> a = 5 >>> b = 5 >>> b == a True >>> b is a True >>> c = 3 + 2 >>> c == a True >>> c is a True >>> d = 10/2 >>> d == a True >>> d is a False #different type! therefore the reference to another object. But... it will not work with special data types like numpy arrays, etc: >>> import numpy as np >>> aa = np.array([1,2,3]) >>> bb = np.array([1,2,3]) >>> aa == bb array([ True, True, True], dtype=bool) >>> aa is bb False
6th Mar 2018, 7:29 AM
strawdog
strawdog - avatar