how to separate a list into two lists?

bud only at fleshwound.org
Sat Aug 6 14:21:40 EDT 2011


On Sat, 06 Aug 2011 10:24:10 -0700, Emile van Sebille wrote:

> On 8/6/2011 10:07 AM smith jack said...
>> 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]
>>
>>
>  >>> L = [('a1', 'b1'), ('a2', 'b2'),('an', 'bn')] zip(*L)
> [('a1', 'a2', 'an'), ('b1', 'b2', 'bn')]
> 

Nice. :)  I forgot about zip, still learning Python myself. 

I'll have to check up on the *L - is that a reference?
I know in Perl, you can assign the lhs to a list,
below works because there are exactly 2 items on the rhs.
Does Python have a catchall, or an ignore the rest?
Example, if L was a tuple that had 3 or more items, 
the below lhs would fail.  Is this possible in Python?


(X,Y) = zip(*L)


X
: ('a1', 'a2', 'an')

Y
: ('b1', 'b2', 'bn')






More information about the Python-list mailing list