The difference between 'is' and '=='

Possible duplicate:
Is there a difference between "foo is None" and "foo == None"?

Pretty simple question.

What's the difference between:

if ab is 'something': 

and

 if ab == 'something': 

Excuse my ignorance

+6
source share
2 answers

The first checks the identity of the second for equality.

Examples:

The first operation using is may or may not result in True based on where these elements are, i.e. strings are stored in memory.

 a='this is a very long string' b='this is a very long string' a is b False 

Checking id () shows that they are stored in different places.

 id(a) 62751232 id(b) 62664432 

The second operation ( == ) will give True , since the lines are equal.

 a == b True 

Another example showing that is can be True or False (compare with the first example), but == works as we expected:

 '3' is '3' True 

this means that both of these short literals were stored in the same memory location, unlike the two longer lines in the above example.

 '3' == '3' True 

No wonder what we would expect.

I believe that is uses id () to determine if the same objects are in memory (see @SvenMarnach's comment below for more details)

+5
source

a is b is true if a and b are the same object. They can compare the same, but be different objects, for example:

 >>> a = [1, 2] >>> b = [1, 2] >>> c = b >>> a is b False >>> a is c False >>> b is c True >>> a == b == c True 
+3
source

Source: https://habr.com/ru/post/917087/


All Articles