Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension to extract multiple fields from list of tuples

Tags:

I have a list of tuples

servers = [('server1', 80 , 1, 2), ('server2', 443, 3, 4)] 

I want to create a new list that only has the first two fields as in:

 [('server1', 80), ('server2', 443)] 

but I cannot see how to craft a list comprehension for more than one element.

hosts = [x[0] for x in servers]  # this works to give me ['server1', server2']  hostswithports = [x[0], x[1] for x in servers] # this does not work 

I prefer to learn the pythonic way vs using a loop - what am I doing wrong?

like image 639
Bill Avatar asked Oct 30 '18 20:10

Bill


2 Answers

You can use extended iterable unpacking.

>>> servers = [('server1', 80 , 1, 2), ('server2', 443, 3, 4)] >>> [(server, port) for server, port, *_ in servers] [('server1', 80), ('server2', 443)] 

Using _ as a throwaway placeholder-name is a common convention.

like image 77
timgeb Avatar answered Sep 22 '22 09:09

timgeb


What you were doing was almost right. You were attempting to translate each tuple in your list into a new tuple. But you forgot to actually declare the tuple. That's what the parentheses are doing:

hosts = [(x[0], x[1]) for x in servers] 
like image 36
Woody1193 Avatar answered Sep 19 '22 09:09

Woody1193