+ 7
What is the output of the code?Also tell how?
A=[1,2,3,4,1] for i in A: A[i]=0 print(A)
10 Answers
+ 10
Devendra Yadav and others in this discussion :
Hi,
At this code we use a "for" loop on a list, for loop in python works as "foreach" loop in other programing languages.
Therefore, this loop takes one by one the members of the list, not their indexes.
So:
Step by step: #A is:[1,2,3,4,1]
1âŁ
for i in A: #i=1
A[1]=0 #result: A is: [1,0,3,4,1]
2âŁ
for i in A: #i=0
A[0]=0 #result: A is: [0,0,3,4,1]
3âŁ
for i in A: #i=3
A[3]=0 #result: A is: [0,0,3,0,1]
4âŁ
for i in A: #i=1
A[1]=0 #result: A is: [0,0,3,0,1]
As you can see, index 2 and 4 are ignored because our list does not include these numbers and therefore the for loop could not access to Their corresponding indexes in the list.
I edit your code here, run it and if my answer and my code were useful, pls. Upvote them. đ
https://code.sololearn.com/cJOd6jLNQy4P/?ref=app
+ 5
Correct code is:
A=[1,2,3,4,1]
for i in range(len(A)):
A[i]=0
print(A)
Run in code playground :
https://code.sololearn.com/cJOd6jLNQy4P/?ref=app
+ 2
I think in this loop every element in the array is set a value 0. So after loop the array is A = [0, 0, 0, 0, 0].
+ 2
Ok, interesting.
+ 2
ââ â Thank u, Now I got the logicđ
+ 1
Dâ˝â˝â˝â˝7âŁ7âŁ7âŁ
No buddy, answer is [0,0,3,0,1] but don't know how.
+ 1
It starts from the first element and changes index 1 which is number 2 to 0
Now it takes the second element which it just last time assigned from 2 to 0 so it changes the first element which is number 1 to 0
Now it changes index 3 which is number 4 to 0
Then it takes the second last element which was 4 but it changed it to zero so it changes the first element.
Because numbers 2 and 4 was changed before it looped them number 3 and 1 remains the same.
+ 1
Toni Isotalo thanks đ
+ 1
I think the main thing that catches folks on this one is thinking that 'i' in the for loop would refer to the index (0-4) whereas it is the value of each item in the sequence even as they are being updated.
A fun experiment is to see the difference in this small change:
A = [1, 2, 3, 4, 1]
for i in list(A):
A[i] = 0
print(A)
0
https://www.sololearn.com/Discuss/1353515/?ref=app
Similar logic