Difference between is and == in python

First look at the following program:
def test():
    # example 1
    a = 'hello'
    b = 'hello'
    print(a is b) # print True
    print(a == b) # print True
    
    # example 2
    a = 'hello world'
    b = 'hello world'
    print(a is b) # output False
    print(a == b) # print True
    
    # example 3
    a = [1, 2, 3]  
    b = a
    print(a is b) # print True
    print(a == b) # print True

Why are some of the above output results the same and some not the same?

The official documentation describes is as an object identity, and == means equality. The role of is is to check whether the identifiers of the objects are consistent, that is, whether the two objects have the same location in memory, and == is used to check whether the two objects are equal.

Let's take a look at the following program that checks the id of each object

def test():
    # example 1
    a = 'hello'
    b = 'hello'
    print(id(a)) # output 2378974396344
    print(id(b)) # output 2378974396344
    print(a is b) # print True
    print(a == b) # print True
    
    # example 2
    a = 'hello world'
    b = 'hello world'
    print(id(a)) # output 2378974396344
    print(id(b)) # output 2033022437424
    print(a is b) # output False
    print(a == b) # print True
    
    # example 3
    a = [1, 2, 3]  
    b = a
    print(id(a)) # output 1641701071688
    print(id(b)) # output 1641701071688
    print(a is b) # print True
    print(a == b) # print True

It is very clear to print out the id result. As long as the values ​​of a and b are the same, the == result outputs True; only the id is the same, the is result outputs True. But there is a question, why the 'hello' a is b of example1 outputs True, while the 'hello world' of example2 outputs False.

This is because Python's string residency mechanism comes into play in the former case. For smaller strings, in order to improve system performance, Python will keep a copy of its value, which can be directly pointed to when creating a new string. So there is only one copy of 'hello' in memory, the id values ​​of a and b are the same, and 'hello world' is a long string that does not reside in memory. Python creates objects to represent a and b, so their values Same, but with different id values. (Some compilers optimize the program, so the is operation may be different).

The comparison of None in actual python, why is is None, not == None?

This is because None is a singleton object in Python. If a variable is None, it must point to the same memory address as None. And __eq__ is called behind ==None, and __eq__ can be overloaded. The following is an example of is not None but == None

class Foo(object):
        def __eq__(self,other):
            return True
    f = Foo()
    print(f is None) # output False
    print(f == None) # print True
Above == is overloaded, so it outputs True.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324857051&siteId=291194637