What is the difference between `==` and `is` in Python?
`==` checks for value equality, while `is` checks for object identity. Use `==` for comparing values and `is` for checking if two references point to the same object.
In Python, understanding the difference between ==
and is
is essential for effective comparison of objects. The ==
operator checks for value equality, meaning it evaluates whether the values of two objects are the same. For example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # Output: True
Here, x
and y
have the same contents, so x == y
evaluates to True
. In contrast, the is
operator checks for object identity, meaning it evaluates whether two references point to the same object in memory:
print(x is y) # Output: False
Even though x
and y
have the same contents, they are different objects in memory. To illustrate further:
z = x
print(x is z) # Output: True
In this case, z
is a reference to x
, so x is z
evaluates to True
. Use ==
when you want to compare the values of objects and is
when you need to check if two references point to the same object.