is vs ==

·

2 min read

is vs ==

In Python, is and == are two different comparison operators.

is is used to test object identity. It checks whether two variables refer to the same object in memory.

== is used to test for value equality. It checks whether the values of two objects are equal.

Here's an example to illustrate the difference:

x = [1, 2, 3]
y = [1, 2, 3]

# Using == to test for value equality
print(x == y)  # Output: True

# Using is to test for object identity
print(x is y)  # Output: False

In the above example, x and y are two separate list objects with the same values. When we use the == operator to compare them, it returns True because their values are equal. However, when we use the is operator to compare them, it returns False because they are different objects in memory.

Note that for certain types of objects, such as integers and strings, small values may be interned and reused by the interpreter, which can make the is and == operators behave differently than expected. For example:

a = 10
b = 10

# Using == to test for value equality
print(a == b)  # Output: True

# Using is to test for object identity
print(a is b)  # Output: True (may vary depending on the implementation)

In the above example, the values of a and b are both 10. When we use the == operator to compare them, it returns True as expected. However, because small integers are interned and reused by the interpreter, a and b actually refer to the same object in memory, so when we use the is operator to compare them, it also returns True.