Python shortcut ?

Santanu Chatterjee santanu at softhome.net
Thu Nov 6 02:35:23 EST 2003


On Sun, 12 Oct 2003 13:21:21 -0700, David Eppstein wrote:

> In article <pan.2003.09.10.19.44.10.270511 at softhome.net>,
>  "Santanu Chatterjee" <santanu at softhome.net> wrote:
> 
>> Suppose I have the following list:
>>     myList = [('a','hello), ('b','bye')]
>> 
>> How do I get only the first element of each tuple in the above list to
>> be printed without using:
>>     for i in range(len(myList)):
>>         print myList[i][0]
>> or:
>>     for i in myList:
>>         print i[0]
>>  
>> I tried:
>>     print myList[:][0]
>> but it seems to have an altogether different meaning.
> 
> If you're set on a one-liner, you could try
> print zip(*myList)[1]
> or
> print [word for letter,word in myList]
> 
> These are no quite the same -- zip makes tuples, the list comprehension
> makes a list.  My own preference would be for the list comprehension --
> it's not as concise, but the meaning is clearer.

Thanks for the solution. I was already using the second solution. 
I did not know about the zip function.

Regards,
Santanu




More information about the Python-list mailing list