Puzzle 13 Identity Crisis
Python Brain Teasers — by Miki Tebeka (22 / 40)
👈 Attention Seeker | TOC | The Great Divide 👉
a, b = 12, 3
x = a * b
y = b * a
print(x is y)
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: True
A Python variable is a name pointing to a Python object. When you have two variables (such as x and y), you can ask two questions:
Equality
Are the objects these variables point to equal? (the == operator)
Identity
Do these two variables point to the same object? (the is operator)
Since you did two separate calculations for x and y, you’d expect them to be equal but not identical. In general, you’d be right. Change the value of b to 333 and re-run; you will see False as the output.
The reason you’re seeing True is due to an implementation detail. Since the small numbers are…