Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python adding every other item

Tags:

python

If I have a list with say [7,6,5,4,3,2,1] how can I make it add upp every second number, for instance 7 + 5 + 3 + 1?

I've tried adding mylist[0] + mylist[2] etc but it is very tedious.

like image 385
willyssignal Avatar asked May 11 '26 09:05

willyssignal


1 Answers

sum(mylist[::2])

the mylist[::2] takes every other item, and sum sums it.

If you want to have the first, third, fifth et cetera item, you can use:

sum(list[1::2])

This will first omit the first item (with the 1 part), then do the same as in the first command.

like image 150
Mathias711 Avatar answered May 12 '26 23:05

Mathias711