- 4
Loop in python for list? Can anybody explain how does this code perform?
A=[1,2,3,4,1] for n in A: A[n]=0 print(A) Result : [0,0,3,0,1]
2 Respuestas
+ 1
Add some print statements like this, and run it again, you will see what happens.
The list values change while the code is running.
A=[1,2,3,4,1]
for n in A:
A[n]=0
print(n,A)
print(A)
+ 1
n is travelling on each value in the list
So when it goes to first value that's 1, it change A[1] that is second element due to 0 based indexing into 0
And therefore when it moves to second value it's already zero due to previous iteration
And it run so on
To understand idexing you can refer :
https://youtube.com/channel/UC3K2nGS4rvTfPlh-Rzx80OA