+ 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)

18th Jun 2018, 6:24 PM
Devendra Yadav
Devendra Yadav - avatar
10 Respuestas
+ 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
19th Jun 2018, 8:25 AM
Root
Root - avatar
+ 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
19th Jun 2018, 9:15 AM
Root
Root - avatar
+ 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].
18th Jun 2018, 6:30 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
Ok, interesting.
18th Jun 2018, 7:18 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
‌‌ ‌ Thank u, Now I got the logic😊
19th Jun 2018, 9:07 AM
Devendra Yadav
Devendra Yadav - avatar
+ 1
D⚽⚽⚽⚽7⃣7⃣7⃣ No buddy, answer is [0,0,3,0,1] but don't know how.
18th Jun 2018, 6:33 PM
Devendra Yadav
Devendra Yadav - avatar
+ 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.
18th Jun 2018, 6:35 PM
Toni Isotalo
Toni Isotalo - avatar
+ 1
Toni Isotalo thanks 😊
18th Jun 2018, 6:39 PM
Devendra Yadav
Devendra Yadav - avatar
+ 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)
18th Jun 2018, 11:33 PM
1_coder
18th Jun 2018, 6:53 PM
李立威