Explain Codes LogoExplain Codes Logo

String comparison in Python: is vs. ==

python
singleton
best-practices
python-quirks
Anton ShumikhinbyAnton Shumikhin·Oct 11, 2024
TLDR

In Python, == checks if the values of two variables are equivalent, while is verifies if they are the exact same object in memory. Use == for comparing contents of items and is for identity checks.

x = [1, 2, 3] y = [1, 2, 3] z = x # z is x in disguise! print(x == y) # True; y is an identical twin of x print(x is y) # False; y is just a very convincing doppelgänger of x print(x is z) # True; z is indeed x in disguise, Sherlock Holmes approves!

When to use is or ==

Dealing with None

When testing if a variable has a value of None, it's preferred to use is because None is a singleton object in Python (meaning there’s only one None sailing the Pythonic seas).

val = do_something_mysterious() if val is None: # It's None for sure, no imposters allowed! handle_mysterious_case()

Boolean checks

For boolean values, clear syntax is king. Use if x: rather than if x == True:.

if sea_is_calm: hoist_sail() # Sail on, me hearties!

Small numbers and is

Python performs optimizations for immutable types like integers, causing some "inflated truths".

a = 256 b = 256 print(a is b) # True, but only by the grace of Python's optimization quirks

NaN: Not an ordinary member

When dealing with NaN (Not a Number), equality checks through == are effectively irrelevant.

import math nan = math.nan print(nan == nan) # False, isNaN joined the Doubt Club: NaN doubts its own identity.

Wise precautions

Immutable vs. mutable battles

In a Pythonic war of immutable vs mutable, choose your weapon of comparison wisely: for immutable objects (str, int, tuple), 'arm' yourself with ==. If dealing with mutable structures (list, dict), remember, appearances can be deceptive; two objects may look alike, but can be distinct entities.

Dodging logical entanglements

Beware of the booby traps of logical errors! Ensure to use is None rather than == None to avoid falling off the Pythonic cliffs.

Infinity War

In the realm of loops or conditions, is not instead of != might open a portal to the Infinite Loop Universe™. Be as fierce as Thanos, and crush infinite loops with !=.

while cash is not infinite: # This can sadly loop forever... keep_working()

The Quirks of Python Interning

Python's string interning can result in misleading outcomes in some cases. Using is for comparison between strings can sometimes return True, but it's nothing more than a trick played by Python's optimization.