Python Interview Questions

32 Questions
Python

Python

Web DevelopmentFrontendBackendData Science

Question 9

What is the difference between == and is operators?

Answer:

In Python, == and is are used for comparison, but they serve different purposes and have different behavior.

== Operator

  • Purpose: The == operator is used to compare the values of two objects to determine if they are equal.

  • Behavior: When you use ==, Python checks if the values or data held by the objects are the same.

  • Usage:

    a = [1, 2, 3]
    b = [1, 2, 3]
    print(a == b)  # Output: True

    In the example above, a and b are two different lists that contain the same values. Therefore, a == b returns True.

is Operator

  • Purpose: The is operator is used to compare the identities of two objects to determine if they refer to the same object in memory.

  • Behavior: When you use is, Python checks if both variables point to the same object (i.e., they have the same memory address).

  • Usage:

    a = [1, 2, 3]
    b = [1, 2, 3]
    print(a is b)  # Output: False

    In the example above, a and b are two different lists with the same values, but they are stored at different memory locations. Therefore, a is b returns False.

Examples and Detailed Explanation

Example with Lists:

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)  # Output: True
print(a is b)  # Output: False

Here, a == b is True because the lists have the same contents. However, a is b is False because a and b refer to different objects in memory.

Example with Integers:

x = 5
y = 5

print(x == y)  # Output: True
print(x is y)  # Output: True

In this example, x == y is True because both integers have the same value. x is y is also True because Python internally caches small integers, so x and y actually refer to the same object in memory.

Example with Strings:

str1 = "hello"
str2 = "hello"

print(str1 == str2)  # Output: True
print(str1 is str2)  # Output: True

Similar to small integers, short strings are also cached by Python. Thus, str1 and str2 not only have the same value but also refer to the same object in memory, making both str1 == str2 and str1 is str2 return True.

Example with Larger Objects:

a = [1, 2, 3]
b = a

print(a == b)  # Output: True
print(a is b)  # Output: True

b.append(4)

print(a == b)  # Output: True
print(a is b)  # Output: True

In this example, b is assigned to reference the same list as a. Therefore, a == b and a is b are both True. Modifying b also modifies a because they are the same object in memory.

Summary

  • == checks for value equality: It determines if the values of two objects are the same.
  • is checks for identity equality: It determines if two references point to the same object in memory.

Understanding the difference between == and is is crucial for avoiding bugs, especially when dealing with mutable objects like lists and dictionaries.

Recent job openings