Search⌘ K
AI Features

How Not to Use the "is" Operator

Explore how the Python is operator works compared to the == operator by examining object identity versus value equality. Learn when and why Python optimizes object allocation, understand version-specific behavior, and avoid pitfalls when using is with integers and other data types.

We'll cover the following...

Let’s learn how to correctly use the is operator in Python.

1.

Can you explain the behavior in the code below?

Python 3.5
>>> a = 256
>>> b = 256
>>> a is b
True # output
>>> a = 257
>>> b = 257
>>> a is b
False # output

Try it out in the terminal below:

Terminal 1
Terminal
Loading...

2.

Let's try a similar thing with data structures.
Python 3.5
a = []
b = []
print(a is b)
a = tuple()
b = tuple()
print(a is b)

3.

Let’s observe the behavior in Python 3.8 versus Python 3.7.

⚠️ The following code is meant for Python 3.8 specifically.

C++
# using Python 3.8
a, b = 257, 257
print(a is b)

⚠️ The following code is meant for Python 3.7 specifically.

C++
# using Python 3.7
a, b = 257, 257
print(a is b)

Explanation

The difference between is and == operators

  • The
...