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

list, loops, python

Solution

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.

Problem

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 ```

Original source

Related problems