unpacking vars from list of tuples

Chris Rebert clp2 at rebertia.com
Tue Sep 15 23:56:49 CEST 2009


On Tue, Sep 15, 2009 at 2:51 PM, Ross <rossgk at gmail.com> wrote:
> I'm inexperienced with some of the fancy list slicing syntaxes where
> python shines.
>
> If I have a list of tuples:
>
>   k=[("a", "bob", "c"), ("p", "joe", "d"), ("x", "mary", "z")]
>
> and I want to pull the middle element out of each tuple to make a new
> list:
>
> myList = ["bob", "joe", "mary"]
>
> is there some compact way to do that?  I can imagine the obvious one
> of
>
> myList = []
> for a in k:
>   myList.append(a[1])
>
> But I'm guessing Python has something that will do that in one line...

Indeed:

myList = [a[1] for a in k]

Google for "list comprehension python".

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list