+ 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
1 Odpowiedź
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