For loops and list reassignment | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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!

24th Jul 2020, 1:32 AM
Alfred Ledore
Alfred Ledore - avatar
4 Respostas
+ 4
Pretty hard to figure that out in the limited time you have in a challenge
24th Jul 2020, 3:21 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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]
24th Jul 2020, 3:20 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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)
24th Jul 2020, 3:05 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Thank you, your explanation helped a lot.
24th Jul 2020, 12:58 PM
Alfred Ledore
Alfred Ledore - avatar