Intern
Intern

Reputation: 39

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)

Upvotes: 0

Views: 47

Answers (2)

Anurag Dhadse
Anurag Dhadse

Reputation: 1873

after assigning a[i]= a[a[i] + 3] the list is now, [5, 2, 3, 4, 5] so, a[a[i] + 3] becomes a[8] which isn't there in the list.

Upvotes: 1

Loocid
Loocid

Reputation: 6441

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.

Upvotes: 2

Related Questions