how to separate a list into two lists?

John Posner jjposner at optimum.net
Sat Aug 6 16:06:41 EDT 2011


On 2:59 PM, smith jack 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?
>

The official Python documentation [1] notes that "zip()
<http://docs.python.org/library/functions.html#zip> in conjunction with
the * operator can be used to unzip a list". Ex:

   >>> L = [ (1,'a'), (2,'b'), (3,'c'), (4,'d') ]
   >>> zip(*L)
   [(1, 2, 3, 4), ('a', 'b', 'c', 'd')]


HTH,
John

[1] http://docs.python.org/library/functions.html

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110806/d0f0e205/attachment.html>


More information about the Python-list mailing list