4

I'm new to python, and I'm trying to get to know the list comprehensions better.
I'm not even really sure if list comprehension is the word I'm looking for, since I'm not generating a list. But I am doing something similar.

This is what I am trying to do:

I have a list of numbers, the length of which is divisible by three.

So say I have nums = [1, 2, 3, 4, 5, 6] I want to iterate over the list and get the sum of each group of three digits. Currently I am doing this:

for i in range(0, len(nums), 3):
    nsum = a + b + c for a, b, c in nums[i:i+3]
    print(nsum)

I know this is wrong, but is there a way to do this? I'm sure I've overlooked something probably very simple... But I can't think of another way to do this.

1
  • So do you want 1+2+3, 4+5+6 or 1+2+3, 2+3+4, 3+4+5,...? Commented Mar 28, 2010 at 10:31

3 Answers 3

6

See sum(iterable[, start]) builtin, and use it on slices.

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings.

>>> nums
[1, 2, 3, 4, 5, 6]
>>> [sum(nums[i:i+3]) for i in  range(0, len(nums),3)]
[6, 15]
>>> 
6
  • +1 exactly my thought but you were faster and your answer is more elaborated :) Commented Mar 28, 2010 at 10:40
  • actually, I get this error: TypeError: sequence index must be integer, not 'slice' Commented Mar 28, 2010 at 10:46
  • @Carson Myers did you type it exactly like above, no brackets placed differently? What python version do you use?
    – extraneon
    Commented Mar 28, 2010 at 11:30
  • 1
    The "sequence" in that exception makes me think that it's some custom sequence that doesn't support slicing. Commented Mar 28, 2010 at 12:26
  • You would get that exception for nums=xrange(1,7) Commented Mar 28, 2010 at 13:17
4
import itertools

nums = [1, 2, 3, 4, 5, 6]

print [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]
1
  • Does your solution have any advantage compared to sum() and sublists (execution time, memory)? I am just curious ;) Commented Mar 28, 2010 at 10:38
1
nums = [1, 2, 3, 4, 5, 6]
map(sum, itertools.izip(*[iter(nums)]*3))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.