Can someone explain why this is the output for this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain why this is the output for this code?

A = [1,2,3,4,1] for n in A: A[n] = 0 print(A) Output: [0,0,3,0,1]

22nd Apr 2018, 6:41 PM
stephanie
stephanie - avatar
2 Answers
+ 1
Firstly I think this is what you are trying to do: for i in range(0, len(A)): A[i] = 0 The reason why the code outputted that is because for n in A: accesses the values in the list so when you do A[n] it goes to that index i.e. in the first iteration it accesses the element of index 1 (2nd element) because that's the first value in the list. Then at the second iteration the 2nd element is 0 which means python will go to the first element of the list and change it to 0, I think you get the point now.
22nd Apr 2018, 7:21 PM
TurtleShell
TurtleShell - avatar
0
Hi, I wrote your code here: https://code.sololearn.com/cIjyyBy6Jw5b/?ref=app With additional print, we can see how you modify your array and what is the impact on your output 😁
22nd Apr 2018, 7:36 PM
jerome