sum for sequences?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Mar 24 22:07:24 CET 2010


On Wed, 24 Mar 2010 15:29:07 +0000, kj wrote:

> Is there a sequence-oriented equivalent to the sum built-in?  E.g.:
> 
>   seq_sum(((1, 2), (5, 6))) --> (1, 2) + (5, 6) --> (1, 2, 5, 6)
> 
> ?

Yes, sum.

help(sum) is your friend.

>>> a = range(2)
>>> b = range(3)
>>> c = range(4)
>>> sum((a, b, c), [])
[0, 1, 0, 1, 2, 0, 1, 2, 3]


Beware though that sum on lists and tuples will be fairly inefficient if 
you have lots of them. You may find that this will be much more efficient:

result = []
for seq in sequences:
    result.extend(seq)



-- 
Steven



More information about the Python-list mailing list