convert list of tuples into several lists

Francis Girard francis.girard at free.fr
Wed Feb 9 14:55:51 EST 2005


Le mercredi 9 Février 2005 14:46, Diez B. Roggisch a écrit :
> zip(*[(1,4),(2,5),(3,6)])
>
> --
> Regards,
>
> Diez B. Roggisch

That's incredibly clever! I would had never thought to use "zip" to do this ! 
I would had only think to use it for the contrary, i.e.

>>> zip([1,2,3], [4,5,6])
[(1, 4), (2, 5), (3, 6)]

Notice though that the solution doesn't yield the exact contrary as we end up 
with a list of tuples instead of a list of lists :

>>> zip(*[(1,4),(2,5),(3,6)])
[(1, 2, 3), (4, 5, 6)]

But this can be easily fix if lists are really wanted :

>>> map(list, zip(*[(1,4),(2,5),(3,6)]))
[[1, 2, 3], [4, 5, 6]]


Anyway, I find Diez solution brillant ! I'm always amazed to see how skilled a 
programmer can get when comes the time to find a short and sweet solution.

One can admire that zip(*zip(*a_list_of_tuples)) == a_list_of_tuples

Thank you
You gave me much to enjoy

Francis girard





More information about the Python-list mailing list