+ 3
Why is this the result
Why when i do: A = [1,2,3,4,1] for n in A: A[n]=1 print(A) It only modify 3 things in the list
4 Respostas
+ 3
On first loop:
n is 1. So, "A[n] = 1" means A[1] = 1
So, A becomes [1, 1, 3, 4, 1]
On second loop:
n is STILL 1 because the second number of "A" list is 1
So, "A[n] = 1" means A[1] = 1
So, A remains as [1, 1, 3, 4, 1]
On third loop:
n is 3 because the third number of "A" list is 3
So, "A[n] = 1" means A[3] = 1
So, A becomes [1, 1, 3, 1, 1]
The rest of the loop doesn't impact anything much.
So, that's why it modifies only 3 things in the list
+ 5
1: A = [1,2,3,4,1]
2: for n in A:
3: A[n]=1
4:print(A)
First time in loop line 2 & 3 n=1 so A=[1,1,3,4,1]
Second time in loop n=1 so no change to A
Third time in loop n=3 so A=[1,1,3,1,1]
Fourth time in loop n=1 so no change to A
Fifth time in loop n=1 so no change to A
+ 2
1st time it is modifing A[1] which is 2 basically
2nd time it is modifying A[1] which is changed to 1 earlier
3rd time it is modifying A[3] which is 4 basically
4th time it is modifing A[1] which is already 1
5th time is is again modifying A[1]
hence it is modifying only 3 times
0
Thanks