...

/

How Not to Use the "is" Operator

How Not to Use the "is" Operator

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?

Press + to interact
>>> 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.
Press + to interact
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.

Press + to interact
# using Python 3.8
a, b = 257, 257
print(a is b)

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

Press + to interact
# using Python 3.7
a, b = 257, 257
print(a is b)

Explanation

The difference between is and == operators

  • The is
...