Home > Backend Development > Python Tutorial > Python None Comparison: 'is' or ==?

Python None Comparison: 'is' or ==?

Mary-Kate Olsen
Release: 2024-11-13 02:51:02
Original
688 people have browsed it

Python None Comparison:

Python None Comparison: "is" or ==?

Comparing variables to None is a common operation in Python. However, you may have noticed a discrepancy in the syntax used, leading to the question of whether to use "is" or ==.

In general, it is recommended to use "is" when comparing variables to None. The reason for this is that "is" checks for object identity, while == checks for object equality. In Python, there is only one None object, so comparing anything to None using "is" will always return True if they are the same object.

On the other hand, == checks for object equality. This means that it will return True if the two objects are equal, even if they are not the same object. For example, consider the following code:

class Negator(object):
    def __eq__(self, other):
        return not other

thing = Negator()
print(thing == None)  # True
print(thing is None)  # False
Copy after login

In this example, the Negator class defines an eq method that returns True when the objects are not equal. When comparing thing to None using ==, the custom eq method is called, resulting in True. However, when comparing using is, we see that they are not the same object, resulting in False.

Therefore, if you are strictly checking whether an object is identical to None (i.e., checking for nullity), it is recommended to use "is". If, however, you are checking for equality (i.e., checking if two objects have the same value), you should use ==.

The above is the detailed content of Python None Comparison: 'is' or ==?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template