31st Aug 2021, 5:11 AM
alagammai uma
alagammai uma - avatar
4 ответов
+ 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.
31st Aug 2021, 5:26 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 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)
31st Aug 2021, 9:39 AM
Lothar
Lothar - avatar
31st Aug 2021, 5:18 AM
Vtec Fan
Vtec Fan - avatar
31st Aug 2021, 4:54 PM
alagammai uma
alagammai uma - avatar