Puzzle 17 Endgame
Python Brain Teasers — by Miki Tebeka (26 / 40)
👈 Call Me Maybe | TOC | Round and Round We Go 👉
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.
This code will print: [’Bruce’, ’Carol’, ’Natasha’, ’Peter’]
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.