+ 1
a=[1,2,3,4,1] for n in a: a[n]=0 print(a)
didn't get it's output.... please explain me the right answer with logic
6 odpowiedzi
+ 3
Oh so it loops through the current values of a not the starting values of a
loop 1 sets the value of a[1] to 0
loop 2 sets value of a[0] to 0
loop 3 sets value of a[3] to 0
at this point we are at
a = [0,0,3,0,1]
0
What were you expecting?
n in a will go through the values in a in order. if you are trying to set every value in the array to 0 then do
for n in range(len(a)):
a[n] = 0
0
Jason Edelson i was expecting the output [1,0,0,0,0]
but the correct output is [0,0,3,0,1]
0
#This code explains itself
a=[1,2,3,4,1]
print(set(range(len(a))))
for n in a:
print(f'{a} a[{n}]={a[n]} -> 0')
a[n]=0
0
Jason Edelson Thanks buddy
0
a=[1,2,3,4,1]
for n in a:
print(n, end=": ")
a[n]=0
print(a)
If you print the n, you will know what happens.
It uses the next element of the updated array.
Interesting to know, I did not know that before 😅
For expected output use:
a=[1,2,3,4,1]
b=a.copy()
for n in a:
print(n, end=": ")
b[n]=0
print(b)