unpacking vars from list of tuples
rossgk at gmail.com
Wed Sep 16 04:12:05 CEST 2009
That's actually the stuff I was trying to remember.
my_list = [name for _, name, _ in k]
I recalled using some underscores for nice dense unnamed variable
unpacking before, but couldn't recall the process.
Thanks for that.
On 15-Sep-09, at 6:33 PM, Tim Chase wrote:
>> 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
>> myList = ["bob", "joe", "mary"]
>> is there some compact way to do that? I can imagine the obvious one
>> myList = 
>> for a in k:
>> But I'm guessing Python has something that will do that in one
> To add some readability to the other suggested solutions, I'd use
> tuple unpacking
> my_list = [name for status, name, code in k]
> Not knowing what  and  are, I randomly designated them as
> "status" and "code", but you likely have your own meanings. If you
> don't, you can always just use the "_" convention:
> my_list = [name for _, name, _ in k]
> # or
> my_list = [name for (_, name, _) in k]
> As an aside, "my_list" is preferred over "myList" in common Python
> practice. I don't know if there's a preferred convention for "with
> vs without" the parens in such a tuple-unpacking list comprehension.
More information about the Python-list