search

What is the difference between "is" and "==" in Python?

In Python, the is operator and the == operator are used for different purposes and have different functionalities:

Object Identity vs. Value Equality:

  • is: The is operator checks whether two variables refer to the same object in memory. It compares the object identity or memory address.
  • ==: The == operator checks whether the values of two variables are equal. It compares the values of the objects.

Usage:

  • is: The is operator is used to determine if two variables refer to the same object. It is often used to compare object identity, especially for mutable objects and instances of custom classes.
  • ==: The == operator is used to compare the values of two objects. It is commonly used for comparing primitive data types like integers, floats, strings, and for comparing values of built-in objects that have a defined notion of equality.

Here's an example to illustrate the difference between is and ==:

a = [1, 2, 3]
b = a  # Both 'a' and 'b' refer to the same object

print(a is b)  # Output: True (both variables refer to the same object)
print(a == b)  # Output: True (both objects have the same values)

c = [1, 2, 3]
print(a is c)  # Output: False (different objects with different memory addresses)
print(a == c)  # Output: True (both objects have the same values)

In this example, a is b returns True because both a and b refer to the same list object in memory. On the other hand, a is c returns False because a and c are two different list objects, even though they have the same values. In both cases, a == b and a == c return True because the values of the objects are equal.

It's important to note that while is checks for object identity, == checks for value equality. Depending on the objects being compared, the == operator might internally call the __eq__() method to determine equality.

In general, use the is operator when you want to check if two variables refer to the same object, and use the == operator when you want to compare the values of two objects for equality.

It's worth mentioning that for built-in immutable objects like integers and strings, small values are often cached and reused by the interpreter, so is might return True for small integer values and short strings due to this optimization. However, this behavior may vary across different Python implementations and versions.

Related Questions You Might Be Interested