+ 2
For loops and list reassignment
I encountered the following code during a challenge: *What is the output* A = [1, 2, 3, 4, 1] for n in A: A[n] = 0 print(A) # output is [0, 0, 3, 0, 1] After looking at the code and the answer and putting it into playground, I was still unsure of why this was the output. I think it has something to do with the for loop, but if someone could clarify I would be grateful. Thanks!
4 ответов
+ 4
Pretty hard to figure that out in the limited time you have in a challenge
+ 3
A[n] = 0 is a list slice which seems to do the following
A = [1,2,3,4,1]
A[n] == A[0] iteration => A[1] slice =2
A = [1,0,3,4,1]
A[n] == A[1] iteration => A[0] slice =1
A = [0,0,3,4,1]
A[n] == A[2] iteration => A[3] slice = 4
A = [0,0,3,0,1]
A[n] == A[3] iteration => A[0] slice = 0
A[0,0,3,0,1]
A[n] == A[4] iteration => A[1] slice = 0
Final result:
A = [0,0,3,0,1]
+ 2
Try running your code like this to see the iterations of A, it may help you understand.
A = [1, 2, 3, 4, 1]
for n in A:
A[n] = 0
print(A)
+ 1
Thank you, your explanation helped a lot.