-1

The below works

a = 0
b = 1
a, b = b, a
print(a, b)  # 1 0

But the below does not work:

l = [3, 6, 9]
a = 0
a, l[a] = l[a], a  # IndexError: list assignment index out of range

How does tuple assignment work in Python?

eteng
  • 9
  • You don't seem to understand the range of subscripts in the list. – Mechanic Pig May 17 '22 at 13:09
  • In `l[a], a` `a` is now 3, which is out of range. – Guy May 17 '22 at 13:10
  • 1
    `l[a]` gets evaluated as 3 and is assigned to `a`, when when trying to assign `a` to `l[a=3]` you get that error as len(l) is only 3 – weasel May 17 '22 at 13:11
  • What do you think this code *should* do (if it "worked"), and why? – Scott Hunter May 17 '22 at 13:12
  • Thanks a lot for your help. As answered in `https://stackoverflow.com/questions/8725673/multiple-assignment-and-evaluation-order-in-python`: In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables, so I thought that: evaluates l[a] (let's call the result x == l[0] == 3), then sets a to x (==3) and l[a] (i.e. l[0]) to a (==0) – eteng May 17 '22 at 13:21

0 Answers0