Talking about is and == Before these two operators differ , The first thing to know is Python There are three basic elements in the object , Namely :id( Identification )、python type()( data type ) and value( value ).is and == They are all used to compare and judge objects , But the content of object comparison and judgment is not the same . Let's see the specific differences .
Python Compare whether two objects are equal in , There are two ways , Simply speaking , The differences are as follows :
is Is to compare whether two references point to the same object ( Reference comparison ).
== Is to compare whether two objects are equal .
>>> a = [1, 2, 3]
>>> b = a
>>> b is a # a Copy the reference to b, They actually point to an object in memory
True
>>> b == a # Of course , Their values are also equal
True
>>> b = a[:] # b adopt a Slice to get a Part of , The slicing operation here reassigns objects ,
>>> b is a # So it doesn't point to the same object
False
>>> b == a # But their values are still equal
True
Realization principle
is The comparison is whether the two are the same object , So the comparison is the memory address (id Are they the same? ).
== It's worth comparing . Immutable object , for example int,str, It compares values directly