How to make a new list of first elements from existing list of lists

40,677

Solution 1

You have two ways

Using a for loop

countries = []

for e in x:
 countries.append(e[0])

or with list comprehensions, which would be in most cases the better option

countries = [e[0] for e in x]

Furthermore, if your data source is a generator (which it isn't in this case), or if you're doing some expensive processing on each element (not this case either), you could use a generator expression by changing the square brackets [] for parenthesis ()

countries = (e[0] for e in x)

This will compute on demand the elements, and if the data source is too long or a generator will also reduce the memory footprint compared to a list comprehension.

Solution 2

The most readable way is probably:

>>> data = [["UK", "LONDON", "EUROPE"],
            ["US", "WASHINGTON", "AMERICA"],
            ["EG", "CAIRO", "AFRICA"],
            ["JP","TOKYO","ASIA"]]
>>> countries = [country for country, city, continent in data]
>>> countries 
['UK', 'US', 'EG', 'JP']

This list comprehension makes it clear what the three values in each item from data are, and which will be in the output, whereas the index 0 doesn't tell the reader much at all.

Solution 3

As cities LONDON, WASHINGTON, CAIRO, TOKYO are present in 1st position(starting from 0) on list items. So get all 1st item from the list items by list compression.

e.g.

>>> x= [["UK", "LONDON", "EUROPE"],["US", "WASHINGTON", "AMERICA"],["EG", "CAIRO", "AFRICA"],["JP","TOKYO","ASIA"]]
>>> [i[1] for i in x]
['LONDON', 'WASHINGTON', 'CAIRO', 'TOKYO']
>>> 

same for countries:

>>> [i[0] for i in x]
['UK', 'US', 'EG', 'JP']
Share:
40,677
Sergiu Costas
Author by

Sergiu Costas

Updated on January 01, 2021

Comments

  • Sergiu Costas
    Sergiu Costas over 3 years

    I have a list below. I need to use it to create a new list with only country names. How do I loop x in order to have a list of country names?

    x = [["UK", "LONDON", "EUROPE"],
         ["US", "WASHINGTON", "AMERICA"],
         ["EG", "CAIRO", "AFRICA"],
         ["JP", "TOKYO", "ASIA"]]
    

    The outcome should look like

    UK
    US
    EG
    JP