Python shortcut ?

David Eppstein eppstein at ics.uci.edu
Sun Oct 12 16:21:21 EDT 2003


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.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list