pythonlistindexoutofrangeexception

Why does this show index out of range even tho all the index are valid?


could someone please explain to me why this does not work, is there some underline issue I am not aware of when doing this?

a = [1, 2, 3, 4, 5]

i = 0
print(i)
print(a[i] + 3)

print(a)
a[i], a[a[i] + 3] = a[a[i] + 3], a[i] # this shows error even tho below is the same and does not
#a[0], a[4] = a[4], a[0]
print(a)

Solution

  • The unpack doesn't all happen at the same time. It unpacks left to right.

    Therefore when you unpack the tuple, you set a[i] = a[a[i] + 3] = 5, then you try to set a[a[i] + 3] = a[i], but a[i] + 3 = 8 which is out of range.