+ 2

Please help

A = [1, 2, 3, 4, 1] for i in A: A[i] = 0 print (A) Why this code output [0, 0, 3, 0, 1] Please answer me. I stuck in it.

4th Aug 2020, 1:55 PM
Allamprabhu Hiremath
4 Respostas
+ 7
(RUN THIS CODE TO GET AN IDEA) A = [1, 2, 3, 4, 1] print(A,end='\n\n') for i in A: print("Original value at index", i,":",A[i]) A[i] = 0 print("After A[i] = 0 gets executed, the value at index", i,"becomes",A[i]) print(A,end='\n\n') print (A) Take my advise please revisit your python lesson especially the lesson on array and how indexing works.
4th Aug 2020, 2:14 PM
minirkk
minirkk - avatar
+ 7
When i run the code i get a result of: [0, 0, 3, 0, 1]
4th Aug 2020, 3:22 PM
Lothar
Lothar - avatar
+ 3
1. i = 1, A[1] = 0, A = [1, 0, 3, 4, 1] 2. i = 2, A[2] = 0, A = [1, 0, 0, 4, 1] 3. i = 0, A[0] = 0, A = [0, 0, 0, 4, 1] 4. i = 4, A[4] = 0, A = [0, 0, 0, 0, 1] 5. i = 1, A[1] = 0, A = [0, 0, 0, 0, 1]
4th Aug 2020, 2:16 PM
Ali Abdelhady
Ali Abdelhady - avatar
+ 2
Lothar I also get [0,0,3,0,1] Ali Abdelhady I think you have made a mistake in 2nd line. In 2nd line i will search for the second value in the list, which is 0. Because in first line the second value was changed into 0 from 2. So it should be 2.i = 0,A[0] = 0, A = [0,0,3,4,1] Though I am confused because your answer actually match with the answer that was given by Allamprabhu Hiremath in the question.
4th Aug 2020, 4:07 PM
Mir Abir Hossain
Mir Abir Hossain - avatar