Academind Logo

List Comprehensions in Python

Lists are a core and easy to create data type in Python. Things get more complex once we want to manipulate multiple list items or filter our data. A great and powerful helper for such tasks (and more) are List Comprehensions.

Created by Manuel Lorenz

List Comprehensions transform an iterable into a different iterable. Doesn't sound too spectacular, does it? Let's find out what List Comprehensions are, how they work and why this transformation is a very useful Python feature you should not miss!

#

Why List Comprehensions?

List Comprehensions are great helpers when it comes to:

The core idea is to access data stored in an existing list. After applying one of the above operations, the result will be stored in a new list while the intial list remains unchanged.

#

Manipulating List Items

Here is a simple list:

my_list = [1, 2, 3]

Your task is to multiply each list item (so 1, 2 and 3) by 2. Easy, right? Unfortunately

my_list = my_list * 2
print(my_list)

returns the following:

my_list = [1, 2, 3, 1, 2, 3]

This leads us nowhere, we need access to each list item instead. In our Python Crash Course you (hopefully) learned that lists are so-called iterables, meaning we can loop through list items with a for loop:

my_list = [1, 2, 3]
for item in my_list:
...

This grants us access to the list items, but for our planned multiplication, additional actions are required:

  • Changing the initial values of the list items

  • Storing these manipulated values

As mentioned before, the changed values should be stored in a new list. Adding data to a list, first requires an initial empty list we can save the data to afterwards, here this list is named double:

double = []
my_list = [1, 2, 3]
for item in my_list:
...

With the ability to loop through our items, we can now use the append() method to add our items to the double list. * 2 multiplies the initial list item value:

double = []
my_list = [1, 2, 3]
for item in my_list:
double.append(item * 2)
print(double)

Printing the double list to the console, confirms that we successfully changed our values and stored these in a new list:

[2, 4, 6]

Ok, but what about List Comprehensions? With these, the same result can be achieved with less code:

my_list = [1, 2, 3]
double = [item * 2 for item in my_list] # highlight-line
print(double)

This shorter syntax results in the same console output, but what's that single line of code now?

  • We loop through each item in my_list with for item in my_list => Our for loop (it is worth mentioning, that item is a name you can choose - it doesn't have to be named item)

  • Each item inside the list should be multiplied by 2 (item * 2)

  • The result of this operation is stored in a new list (note the square brackets around our code) named double

The order of the different code parts is crucial though. You always start with the expression desribing the operation that should be applied to our list items (here item * 2), followed by the for loop to get access to the list items (optionally also followed by another for loop and/or an if statement, more on that in a few seconds).

The shorter List Comprehension syntax makes creating an initial empty list and using the append() method obsolete. We're not limited to manipulating list items though, we can also extract data from lists.

#

Extracting Data From Lists

This is our next example:

users = [{'name': 'Manuel', 'age': 31}, {'name': 'Max', 'age': 30}, {'name': 'Dirk', 'age': 38}]

This list contains three dictionaries as list items. In case you want to learn how to access nested dictionary keys, this video gets you up to speed.

Your task: Create a new list which contains the names only. We can use our previously learned List Comprehension syntax here, this time we won't change a value though, we just want to access it:

users = [{'name': 'Manuel', 'age': 31}, {'name': 'Max', 'age': 30}, {'name': 'Dirk', 'age': 38}]
user_name = [user['name'] for user in users] # highlight-line
print(user_name)

Again we combine three tasks in this single line of code to print 'Manuel', 'Max' and 'Dirk':

  • Looping through each item (here a variable named user) in our users list => for user in users

  • Accessing the user key and returning the name value => user['name']

  • Storing the information in a new list user_name

Of course we could achieve the same result with a for loop as seen in the first example too, but the single line code again is shorter, easier to understand and results in a more efficient code execution.

#

Filtering Data Based on Single or Multiple Conditions

With List Comprehensions it's also possible to filter data according to one or multiple filter critera. Thinking back of our previous users list, the next task is to store all names, but only if the corresponding age value is above 30:

users = [{'name': 'Manuel', 'age': 31}, {'name': 'Max', 'age': 30}, {'name': 'Dirk', 'age': 38}]
user_name = [user['name'] for user in users if user['age'] > 30] # highlight-line
print(user_name)

Again it's pretty straight forward - we just added our if condition (if user['age'] > 30) at the end of our List Comprehension code and used it to filter our list items - therefore only 'Manuel' and 'Dirk' get printed to the console.

We're also not limited to a single condition:

user_name = [user['name'] for user in users if user['age'] > 30 and user['name'] == 'Dirk']

This code will only return the user Dirk as both conditions (user['age'] > 30 and user['name'] == 'Dirk') are true here.

#

Nested List Comprehensions

List Comprehensions also work with so-called nested lists:

user_groups = [
[
{'name': 'Manu', 'age': 31},
{'name': 'Max', 'age': 30}
],
[
{'name': 'Sarah', 'age': 29},
{'name': 'Julie', 'age': 32}
]
]

This time we have a list containing two lists. Each of those lists again holds two dictionaries. Your next task is to store the names of all users in a new list.

We know that we can access list items with for loops. In case of the nested lists, we need two consecutive for loops to access our list items. Following the same logic we previously saw for our if condition, we thankfully also can add the second for loop after the initial one in our List Comprehension:

user_name = [person['name'] for group in user_groups for person in group]
print(user_name)

for group in user_groups grants us access to the two list items inside our user_groups list. With the second for loop we access the dictionaries inside these lists. person['name'] returns the value of the 'name' key.

Of course we can also add one or more filter criteria here. let's again use our age filter:

user_name = [person['name'] for group in user_groups for person in group if person['age'] > 30]
print(user_name)

This only prints 'Manu' and 'Julie' to the console.

As you saw, List Comprehensions are not necessarily required as we can generally achieve the same results with "normal" for loops. However, with List Comprehensions we write less and more efficient code, so diving deeper into them is definitely a helpful next step if you're getting started with Python.

Recommended Courses