Difference Between 'and' & 'is' Operator in Python



In Python, the == and is operators are used for comparison, but they serve different purposes. The == operator checks for equality of values, which means it evaluates whether the values of two objects are the same.

On the other hand, the is operator checks for identity, meaning it determines whether two variables point to the same object in memory. Before discussing the differences between the == and is operators in Python, let's first understand these operators in detail.

What Is the 'is' Operator?

The Python is operator tests whether two variables refer to the same object in memory. If the variables refer to the same memory location, it returns True; otherwise, it returns False. This operator is commonly used to check object identity rather than object equality.

Example

The following is an example of the is operator in Python ?

# Initializing variables
var1 = True
var2 = True
# Using 'is' 
result_1 = var1 is var2
print("The 'is' operation between var1 and var2:", result_1)

Following is the output of the above code:

The 'is' operation between var1 and var2: True

What Is the '==' Operator?

The equality (= =) operator compares two objects based on their values. If both objects have the same values, the equality operator returns True; otherwise, it returns False. The equality operator focuses on the contents or values of the objects being compared.

Example

Following is an example of the == operator in Python ?

# Initialized tuples
Tup1 = ("Python", "Java", "CSS")
Tup2 = ("Python", "Java", "CSS")
# Equality operator
result = Tup1 == Tup2
print("Tup1 == Tup2:", result)

Following is the output of the above code ?

Tup1 == Tup2: True

Difference Between is and (==) operators

The is operator and the equality (==) operator are both used to compare two variables. The key difference is that the is operator checks whether the variables refer to the same memory location, while the equality (==) operator compares the values of the objects.

Example

In the following example, we can observe the difference between the is and == operators ?

# Initialized lists
List1 = ["Python", "Java", "CSS"]
List2 = ["Python", "Java", "CSS"]
# 'is' operator
result_1 = List1 is List2
# Equality operator
result_2 = List1 == List2
print("List1 is List2:", result_1)
print("List1 == List2:", result_2)

Following is the output of the above code ?

List1 is List2: False
List1 == List2: True
Updated on: 2024-12-17T14:35:04+05:30

925 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements