Efficiently Split A List of Tuples

Peter Hansen peter at engcorp.com
Wed Jul 13 20:53:58 EDT 2005


Richard wrote:
> I have a large list of two element tuples.  I want two separate
> lists: One list with the first element of every tuple, and the
> second list with the second element of every tuple.

Variant of Paul's example:

a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10))
zip(*a)

or

[list(t) for t in zip(*a)] if you need lists instead of tuples.

(I believe this is something Guido considers an "abuse of *args", but I 
just consider it an elegant use of zip() considering how the language 
defines *args.  YMMV]

-Peter



More information about the Python-list mailing list