Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

is vs == in Python

Understanding is vs == in Python: Key Differences

8 min readSep 9, 2024

--

Press enter or click to view image in full size

Introduction

In Python, both is and == are used for comparisons, but they serve different purposes and work in distinct ways. Understanding the difference between these two operators is crucial for writing correct and efficient Python code. Misusing them can lead to subtle bugs that are difficult to debug, especially for those new to Python.

Hi my name is CyCoderX and in this article, we’ll explore the differences between is and ==, how they work, and when to use each. By the end, you’ll have a clear understanding of value equality versus identity equality, and how to apply these concepts in your Python projects.

Did you know that you can clap up to 50 times ? Well now you do! Please consider helping me out by clapping and following me! 😊

Understanding == in Python

The == operator in Python is used to compare the values of two objects to determine if they are equal. When you use ==, you’re asking Python whether the values held by the two objects are the same.

What == Compares

  • Value Equality: The == operator checks if the values of the objects on either side of the operator are equal. It does not care about whether the objects are the same instance in memory; it only compares the content.

Example:

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

print(a == b) # Output: True

In this example, a and b are two separate lists, but == returns True because the values contained in both lists are the same.

Usage Examples

  • Comparing Numbers:
x = 10
y = 10

print(x == y) # Output: True
  • Comparing Strings:
str1 = "hello"
str2 = "hello"

print(str1 == str2) # Output: True
  • Comparing Lists:
list1 = [1, 2, 3]
list2 = [1, 2, 3]

print(list1 == list2) # Output: True

In all these examples, == checks whether the values on both sides of the operator are equal.

Understanding is in Python

The is operator in Python checks whether two variables point to the same object in memory. This means that is is used for identity comparison, not value comparison. When you use is, you’re asking Python whether the two variables reference the exact same object.

What is Compares

  • Identity Equality: The is operator checks if the two operands refer to the same object in memory. It doesn’t compare the values of the objects, but rather whether the references are to the same memory location.

Example:

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

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

In this example, a and b are two different lists with the same content, so a is b returns False. However, c is a reference to the same list as a, so a is c returns True.

Usage Examples

  • Comparing Integers (Small Integers):
x = 1000
y = 1000

print(x is y) # Output: False
  • Comparing Strings (Interned Strings):
str1 = "hello"
str2 = "hello"

print(str1 is str2) # Output: True
  • Comparing Lists:
list1 = [1, 2, 3]
list2 = list1

print(list1 is list2) # Output: True

In these examples, is checks if the variables refer to the same object in memory, not whether their values are the same.

Press enter or click to view image in full size
Photo by Lyman Hansel Gerona on Unsplash

Key Differences Between is and ==

Understanding the difference between is and == is crucial to avoid common pitfalls in Python programming.

Value Equality vs. Identity Equality

  • ==: Compares the values of two objects. If the values are the same, == returns True, even if the objects are different instances in memory.
  • is: Compares the identity of two objects. If the two variables point to the same object in memory, is returns True.

Example:

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

print(a == b) # True: Values are the same
print(a is b) # False: Different objects in memory

In this example, a == b returns True because their values are the same, but a is b returns False because they are different objects.

Common Pitfalls and Misconceptions

  • Immutable Objects (like strings and small integers): Python often reuses objects for small integers and interned strings, which can lead to confusion. For example, is might return True for small integers or certain strings even if they are created separately, because Python optimizes by reusing the same object in memory.

Example:

x = 256
y = 256

print(x is y) # Output: True (Python reuses small integers)
  • Mutable Objects (like lists and dictionaries): Since lists and dictionaries are mutable, is will typically return False when comparing two objects with the same values, as they are stored in different memory locations.

Example:

list1 = [1, 2, 3]
list2 = [1, 2, 3]

print(list1 is list2) # Output: False (Different memory locations)

When to Use is vs. ==

Knowing when to use is and == depends on what you’re trying to achieve.

Practical Scenarios for ==

  • Comparing Values: Use == when you need to check if two variables have the same value, regardless of whether they are the same object in memory.
  • Commonly Used with Built-in Types: == is commonly used with numbers, strings, lists, and other built-in types to check for value equality.

Example:

name1 = "Alice"
name2 = "Alice"

if name1 == name2:
print("The names are the same.")

# Output: The names are the same

Practical Scenarios for is

  • Checking for Singleton Objects: Use is when you want to check if two variables point to the same object. This is especially useful when checking for None or other singleton objects.
  • Identity Checks: Use is for identity checks when it’s important to know if two variables reference the exact same object in memory.

Example:

a = None

if a is None:
print("a is None")

In this case, is is used to check if a is the None object, which is a common use case.

Practical Examples and Best Practices

To further clarify when to use is and ==, let's explore some practical examples and best practices that demonstrate their proper usage in different contexts.

Example 1: Comparing Values in Lists

When comparing two lists, use == to check if they contain the same elements, and use is to check if they refer to the same object.

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2) # Output: True (same values)
print(list1 is list2) # Output: False (different objects)
print(list1 is list3) # Output: True (same object)

Best Practice:
Use == when you care about the contents of the lists and is when you need to confirm that two variables point to the same list in memory.

Example 2: Comparing Strings

Strings in Python are immutable, and the Python interpreter may optimize memory usage by reusing the same string object. However, it’s still important to understand the difference between is and ==.

str1 = "hello"
str2 = "hello"
str3 = "".join(["he", "llo"])

print(str1 == str2) # Output: True (same values)
print(str1 is str2) # Output: True (same object due to interning)
print(str1 == str3) # Output: True (same values)
print(str1 is str3) # Output: False (different objects)

Best Practice:
Always use == to compare the values of strings, as this is the correct way to check for value equality. Relying on is can lead to unexpected behavior, especially with non-interned strings.

Example 3: Checking for None

One of the most common and recommended uses of is is to check if a variable is None. Since None is a singleton in Python, it’s always safe and efficient to use is for this check.

a = None

if a is None:
print("a is None")

Best Practice:
Always use is when checking for None. This is more explicit and preferred over using ==.

Example 4: Identity Checks with Custom Objects

Consider a scenario where you have two objects of a custom class with the same attributes. You can use == to compare their values and is to check if they are the same instance.

class MyClass:
def __init__(self, value):
self.value = value

obj1 = MyClass(10)
obj2 = MyClass(10)
obj3 = obj1

print(obj1 == obj2) # Output: False (unless __eq__ is overridden)
print(obj1 is obj2) # Output: False (different objects)
print(obj1 is obj3) # Output: True (same object)

Best Practice:
Use is when you need to confirm that two variables point to the exact same instance of an object. Use == to compare the values, which may require overriding the __eq__ method in custom classes.

Conclusion

Understanding the difference between is and == is crucial for writing clear and bug-free Python code. The == operator should be used for comparing values, checking whether the contents of two objects are the same. On the other hand, the is operator is used for identity comparison, determining whether two variables point to the same object in memory.

Get CyCoderX’s stories in your inbox

Join Medium for free to get updates from this writer.

Knowing when to use each operator helps you avoid common pitfalls and ensures that your code behaves as expected. Whether you’re comparing numbers, strings, lists, or custom objects, applying the right operator in the right context will lead to more reliable and maintainable Python code.

Thank you for reading! If you have any further questions or need clarification on other Python concepts, feel free to ask!

Press enter or click to view image in full size
Photo by Mark Fuller on Unsplash

Final Words:

Thank you for taking the time to read my article!

This article was first published on medium by CyCoderX.

Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!

Join me as we explore the exciting world of AI, tech, data, and beyond!

What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

CyCoderX
CyCoderX

Written by CyCoderX

Machine Learning & Data Engineer | Data Science | Python & SQL | AI | Software Developer | Azure & AWS Cloud Specialist | Blogger simplifying Big Data & Trends

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.