+ 1
Y all elements doesn't become 0 ?
Python lists https://code.sololearn.com/cvR6Yjb68cUn/?ref=app
4 odpowiedzi
+ 3
a=[1,2,3,4,1]
for n in a:
print(n)
"""
you are looping through the values within the list.
output:
1
2
3
4
1
slicing index starts at 0, but first value in loop is 1 and selects second value
a[1]=2->0 #this changed the second value to 0
a[0]=1->0 #now second value is 0 instead of 2 and changes first value to 0
a[3]=4->0 #the third item is 3, which selects the 4 item in the list and changes that to 0
a[1]=0->0 #select second value again
"""
# if you want to change all values to 0, this would be a better way.
for n in range(len(a)):
a[n]=0
print(a)
i hope this makes sense.
+ 5
alagammai uma ,
as the first list element is 1, the code will replace index 1 with 0. so indexing this way may not work always as expected.
you can use enumerate() function inside the for loop to get the list elements plus additionally an index of the current element. this will do the job:
a=[1,2,3,4,1]
for index, n in enumerate(a):
a[index]=0
print(a)
+ 2