Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Equality: How to Check Values Without is

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

In Python, == checks whether two values are equal, while is checks whether two variables point to the same object in memory. Most of the time you want value equality, not identity. This guide shows you how to use == correctly, handle edge cases like floats and custom objects, and avoid common pitfalls.

What You'll Need

  • Python 3.x installed (any recent version)
  • A text editor or Python REPL to test examples

Step-by-Step

  1. Use the == operator for basic value comparison. Write a == b to check if a and b have the same value. This works for numbers, strings, lists, tuples, dictionaries, and most built-in types. For example, 5 == 5 returns True, and [1,2] == [1,2] returns True.
  2. Compare strings by content, not by object identity. Strings are often interned in CPython, so is might sometimes return True for equal strings, but that is an implementation detail. Always use == for string comparison: "hello" == "hello".
  3. For numeric types, == handles type conversion automatically. 1 == 1.0 returns True because both represent the same numeric value. If you need to ensure both are the same type, use type(a) == type(b) in addition to a == b.
  4. Compare lists and tuples element-wise. [1,2] == [1,2] returns True because Python compares each element in order. The same applies to tuples. For sets, order does not matter: {1,2} == {2,1} is True.
  5. Compare dictionaries by key-value pairs. {'a':1} == {'a':1} returns True regardless of insertion order. Dictionaries compare equal if they have the same keys and each key maps to equal values.
  6. For floating-point numbers, consider using a tolerance. Due to binary representation, 0.1 + 0.2 == 0.3 returns False. Instead, use abs((0.1 + 0.2) - 0.3) < 1e-9 or the math.isclose() function: import math; math.isclose(0.1+0.2, 0.3).
  7. Compare custom objects by overriding __eq__. If you define a class, Python uses the default __eq__ which compares object identity (like is). To make == compare values, define __eq__ in your class. For example:
    class Point:
        def __init__(self, x):
            self.x = x
        def __eq__(self, other):
            if isinstance(other, Point):
                return self.x == other.x
            return NotImplemented
    Then Point(1) == Point(1) returns True.
  8. When comparing to None, use is (but that's an exception). The question asks about not using is, but for None specifically, is None is the recommended idiom. If you must avoid is, you can use == None, but it may trigger __eq__ on custom objects and is generally discouraged. For this guide, just note that == works for None too: x == None.
  9. Use != for inequality. The opposite of == is !=. It also checks value inequality, not identity.

Common Mistakes

  • Using is for value comparison. This is the most common mistake. is checks identity, so [] is [] is False even though both are empty lists.
  • Assuming == always works for floats. Floating-point precision issues can cause == to return False for mathematically equal values. Always use a tolerance or math.isclose() for floats.
  • Comparing different types without checking. 1 == "1" returns False because the types differ. If you want to treat them as equal, convert explicitly.
  • Forgetting to override __eq__ in custom classes. Without it, == behaves like is.

Tips

  • Use math.isclose() for float comparisons. It handles relative and absolute tolerances, making your comparisons robust.
  • For NumPy arrays, use np.array_equal() or np.allclose(). The == operator on NumPy arrays returns an element-wise boolean array, not a single boolean.
  • Chain comparisons for readability. a == b == c checks that all three are equal.
  • Remember that == can be overridden. Be aware that custom classes may define __eq__ to do something unexpected, so read the documentation.

Troubleshooting

If == does not return what you expect:

  • Check the types. Use type(a) and type(b) to see if they differ. If they are different, == might return False even if values look similar.
  • Check for float precision. Print the full representation: repr(0.1+0.2) shows 0.30000000000000004. Use math.isclose().
  • For custom objects, verify __eq__ is defined. If not, == falls back to identity. Add __eq__ or use a different comparison method.
  • If comparing lists or dicts, ensure the elements are comparable. If elements are custom objects, they need __eq__ as well.
  • If you get a ValueError with NumPy arrays, use np.array_equal() instead of ==.

Frequently Asked Questions

What is the difference between == and is?

== compares values (what the objects contain), while is compares identity (whether two variables reference the same object in memory).

Can I use == to compare two lists of custom objects?

Yes, but only if the custom objects define __eq__. Without it, list comparison will use identity for each element, so two lists with identical-looking objects will not be equal.

Why does 0.1 + 0.2 == 0.3 return False?

Because floating-point numbers are stored in binary and cannot represent some decimal fractions exactly. The sum is actually 0.30000000000000004. Use math.isclose() for such comparisons.

Does == work for comparing strings with different Unicode normalization?

No, == compares code points, so "é" (precomposed) and "é" (combining) are not equal. Use unicodedata.normalize() to normalize before comparing.

Can I compare two dictionaries with ==?

Yes, dictionaries compare equal if they have the same keys and each key maps to equal values, regardless of insertion order.

Is it ever acceptable to use is for value comparison?

Only for None and sometimes for small integers or interned strings, but that is an implementation detail. Always use == for value comparison to be safe and clear.