w3resource

What is the difference between == and identity (is) in Python?

Python Comparison: "==" vs. "is"

In Python, the "==" operator and the is operator are used for different purposes and perform distinct types of comparison:

"==" Operator (Equality):

  • The "==" operator is used for value comparison.
  • It checks whether two objects have equal values, i.e., the same content.
  • When comparing built-in data types (integers, strings, floats, etc.), "==" checks if their values are equal.
  • For custom objects or user-defined classes, you can customize "==" behavior by implementing the eq() method.

Example using == operator:

Code:

x = 99
y = 98
if x == y:
    print("x and y are equal.")
else:
    print("x and y are not equal.")

Output:

x and y are not equal.

"is" Operator (Identity):

  • The "is" operator is used to determine the identity of objects.
  • It checks whether two variables refer to the same object in memory.
  • It returns True if the objects have the same memory address, indicating they are the same object.
  • It returns False if the objects have different memory addresses, indicating they are different objects.

Example using "is" operator:

Code:

nums = [1, 2, 3, 4, 5]
y = nums
if nums is y:
    print("nums and y refer to the same object.")
else:
    print("nums and y refer to different objects.")

Output:

nums and y refer to the same object.

In the above example, "nums" and "y" refer to the same list object in memory, so the output will be "nums and y refer to the same object."



Follow us on Facebook and Twitter for latest update.