Reputation: 59
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.
Upvotes: 3
Views: 11844
Reputation: 180391
If you don't want to create a new list you can use xrange adding every even indexed element:
l = [7,6,5,4,3,2,1]
print(sum(l[i] for i in xrange(0, len(l), 2)))
Or use itertools.islice
:
sum(islice(l, 0, None, 2))
Some timings show islice wins on time and space using python2:
In [14]: timeit sum(islice(l, 0, None, 2))
10 loops, best of 3: 123 ms per loop
In [15]: timeit sum(l[i] for i in xrange(0,len(l), 2))
1 loops, best of 3: 363 ms per loop
In [16]: timeit sum(l[::2])
10 loops, best of 3: 148 ms per loop
And they all return the same result:
In [21]: sum(islice(l, 0, None, 2))
Out[21]: 24999995000000
In [22]: sum(l[i] for i in xrange(0,len(l), 2))
Out[22]: 24999995000000
In [23]: sum(l[::2])
Out[23]: 24999995000000
Upvotes: 2
Reputation: 6658
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.
Upvotes: 11