Puzzle 17 Endgame

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Call Me Maybe | TOC | Round and Round We Go 👉

avengers.py

​1: avengers = [​'Bruce'​, ​'Carol'​, ​'Natasha'​, ​'Tony'​]
​2: idx = 3
​3: avengers[idx], idx = ​'Peter'​, 2
​4: ​print​(avengers)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print: [’Bruce’, ’Carol’, ’Natasha’, ’Peter’]

images/hline.png

You’re doing multiple assignments, also known as unpacking. In line 3, Python will first evaluate the right side of the = from left to right and then assign to the left side, again from left to right.

In the line avengers[idx], idx = ’Peter’, 2, Python first evaluates avengers[idx] = ’Peter. Since idx is still 3 here, the fourth item on the list, Tony, is being replaced. Then Python will evaluate idx = 2.

This is confusing and considered bad practice. Don’t do it.

Further Reading

--

--

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.