Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10977

Re: how to separate a list into two lists?

References <CAN1Fwxcdtt0u_TT=civMes1hA2qvfkH2YckES7B7qRE++DXzJQ@mail.gmail.com>
Date 2011-08-06 18:14 +0100
Subject Re: how to separate a list into two lists?
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1984.1312650859.1164.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Aug 6, 2011 at 6:07 PM, smith jack <thinke365@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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: how to separate a list into two lists? Chris Angelico <rosuav@gmail.com> - 2011-08-06 18:14 +0100
  Re: how to separate a list into two lists? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-07 10:27 +1000

csiph-web