Puzzle 13 Identity Crisis

Python Brain Teasers — by Miki Tebeka (22 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Attention Seeker | TOC | The Great Divide 👉

identity.py

​ 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.

images/hline.png

This code will print: True

images/hline.png

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…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.