From: kj on


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)

?

(By "sequence" I'm referring primarily to lists and tuples, and
excluding strings, since for these there is ''.join()).

TIA!

~K
From: Glazner on
On Mar 24, 5:29 pm, kj <no.em...(a)please.post> 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)
>
> ?
>
> (By "sequence" I'm referring primarily to lists and tuples, and
> excluding strings, since for these there is ''.join()).
>
> TIA!
>
> ~K

try itertools.chain
From: Neil Cerutti on
On 2010-03-24, kj <no.email(a)please.post> 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)
>
> ?
>
> (By "sequence" I'm referring primarily to lists and tuples, and
> excluding strings, since for these there is ''.join()).

reduce, or functools.reduce in Python 3.1.

>>> functools.reduce(operator.add, ((1, 2), (5, 6)))
(1, 2, 5, 6)

--
Neil Cerutti
"It's not fun to build walls. But it's even less fun to live
without walls in a world full of zombies." --Greedy Goblin
From: Steve Holden on
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)
>
> ?
>
> (By "sequence" I'm referring primarily to lists and tuples, and
> excluding strings, since for these there is ''.join()).
>
Do you mean you want to flatten a list structure? There have been
several discussions about this, which Google will find for you quite easily.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

From: Duncan Booth on
kj <no.email(a)please.post> 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)
>
> ?
>
Apart from the suggestions for Google for general list flattening, for this
specific example you could just use the 'sum' built-in:

>>> sum(((1, 2), (5, 6)), ())
(1, 2, 5, 6)

Just give it an empty tuple as the starting value.