listcomprehension, add elements?

Maric Michaud maric at
Mon Jun 23 13:16:38 CEST 2008

Le Monday 23 June 2008 11:39:44 Boris Borcic, vous avez écrit :
> John Machin wrote:
> > Instead of sum(a + b for a, b in zip(foo, bar))
> > why not use sum(foo) + sum(bar)
> > ?
> or even sum(foo+bar) as may apply.

Because some are better than others :

sum(foo+bar) is the worst, it create a superfluous list of len(foo) + len(bar) 

sum(a + b for a, b in zip(foo, bar)), creates a list of max(len(foo), 
len(bar)) elements, in most cases it is the same as the former.

This could have been corrected using itertools.izip.

So the winner is sum(foo) + sum(bar), which does not create anything not 

But if the question is "how to build the list and sum up all elements in a 
efficient way for sequences of arbitrary length ", it's important to make it 
in the same iteration, so the most effective/clear, and so "pythonic", way to 
do this is (untested) :

res, sum = [], 0
for s in (a + b for a, b 
                        in zip(itertools.izip(xrange(1, 51),
                                                     xrange(50, 0, -1)))):
    sum += s

Which is "pythonic" in first place is to provide sequences of datas as 
iterators when they can grow in size.


Maric Michaud

More information about the Python-list mailing list