+ 1

Could you please explain this output?

a=[8,4,6,1] del(a[1::3]) print(sum(a)) sum is 15 but what exactly is deleting with 1::3 does this mean it is deleting only the first index element? in our case 4

26th Nov 2019, 7:47 PM
THEGreatGatsby
THEGreatGatsby - avatar
1 Odpowiedź
+ 9
The code: del(a[1::3]) uses a slice [1::3]. This means deleting started at index 1 (number 4), up to the end of the list, but step is 3. So only every third index is deleted. As list has index 0 to 3, and the first index to delete is 1, the next index to delete would be 4, but this index does not exist. So the only index that is deleted is 1. list is now [8,6,1] which is 15 in summation.
26th Nov 2019, 8:07 PM
Lothar
Lothar - avatar