How Not to Use the "is" Operator
We'll cover the following...
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?
>>> a = 256>>> b = 256>>> a is bTrue # output>>> a = 257>>> b = 257>>> a is bFalse # output
Try it out in the terminal below:
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.8a, b = 257, 257print(a is b)
⚠️ The following code is meant for Python 3.7 specifically.
C++
# using Python 3.7a, b = 257, 257print(a is b)
Explanation
The difference between is and == operators
- The
isoperator checks if both the operands refer to the same