+ 1

Why such an output?

a=[1,2,3,4,1] for n in a: a[n]=0 print (a) output: 0 0 3 0 1 I thought that a[1]=0, so 2=0 a[2]=0, so 3=0 a[3]=0, so 4=0 a[4]=0, so 1=0 isn't it?

29th Aug 2018, 10:39 AM
Hlad
Hlad - avatar
3 Answers
+ 2
First iteration a[1] = 0 causes a = [1,0,3,4,1]. Second iteration a[0] = 0 causes a = [0,0,3,4,1]. # here is a[0] because values of the array have already been changed above in the first iteration Third iteration a[3] = 0 causes a = [0,0,3,0,1]. Respectively fourth and fifth iterations set 0 to 1st and 2nd element of the array that have already been set. This code does not set 0's for all the elements of the array. You should make a loop for a range 0...5 to do so. These are different things.
29th Aug 2018, 10:56 AM
Steppenwolf
Steppenwolf - avatar
+ 2
The contents of a change, while the loop is running, so it is: a[1]=0, so 2=0 a[0]=0, so 1=0 a[3]=0, so 4=0 a[0]=0, so 0=0 a[1]=0, so 0=0
29th Aug 2018, 10:51 AM
Paul
Paul - avatar
0
Finally got it! Thank u so much!
29th Aug 2018, 11:53 AM
Hlad
Hlad - avatar