how to separate a list into two lists?

Chris Angelico rosuav at gmail.com
Sat Aug 6 13:14:16 EDT 2011


On Sat, Aug 6, 2011 at 6:07 PM, smith jack <thinke365 at gmail.com> wrote:
> if a list L is composed with tuple consists of two elements, that is
> L = [(a1, b1), (a2, b2) ... (an, bn)]
>
> is there any simple way to divide this list into two separate lists , such that
> L1 = [a1, a2... an]
> L2=[b1,b2 ... bn]
>
> i do not want to use loop, any methods to make this done?

One easy way is to use list comprehensions. Technically that'll
involve a loop, but the loop is handled efficiently under the hood.

L1 = [x[0] for x in L]
L2 = [x[1] for x in L]

Another way would be to construct a dictionary from your list of
tuples and then use the keys() and values() of that dictionary to form
your lists (use collections.OrderedDict if the order matters). But I
think the list comps are the best way.

ChrisA



More information about the Python-list mailing list