Python List Comprehensions Made Simple

Dylan | Jan 05, 2020

Post Thumbnail

List comprehensions provide an efficient way to generate lists in Python, allowing us to condense several lines of code into a single easy-to-read line. After reading this post, you’ll have all the tools required to write the following snippet in a single line.

my_list = []
for i in another_list:
if i%2 == 0:

Before we can write a list comprehension to handle all that logic, we’ll have to cover some basics. Let’s dive in.

Basic Syntax

The basic syntax for list comprehensions in Python is:

new_list = [item for item in another_list]

This line of code allows us to generate a copy of another list. The first 'item' is the value that will be “appended” to our new list. Note that it does not matter what we call 'item', just as it doesn’t matter what we call the iteration variable in a loop (e.g. i, index, user). This list comprehension achieves the same result as the following three lines of code:

new_list = []
for item in a_list:

It’s also possible to apply a function to the item before “appending” it to the new list in the list comprehension.

Applying Functions to List Items

List comprehensions can do the work of Python’s built-in reduce() function which applies a function to every item in a list. If we had a list of integers (named integer_list) and wanted to apply a function named square() to every integer and store the outputs in a new list (named squares), we could use the following list comprehension:

def square(number):
return number**2
squares = [square(num) for num in integer_list]

Boolean Logic in List Comprehensions

List comprehensions can also be used to perform the same task as Python’s built-in filter() function. If another list contained a collection of single characters, we could easily create a copy of that list with certain characters removed. For the following example, let’s pretend we want to remove the letters 'a' and 'z'.

new_list = [char for char in another_list if char not in 'az']

When no else statement is required, the if statement is placed at the end of the list comprehension; however, if we wanted to incorporate an else statement, our list comprehension structure changes a bit.

For the following example, imagine we would like to make a boolean list to represent vowels and consonants from a list of characters. Indices in the new list with the value True would convey that the item at the same index in the original list is a vowel, while False values represent consonants at their respective indices. We could build this boolean list using a single list comprehension.

new_list = [True if char in 'aeoiu' else False for char in a_list]

The same effect can also be achieved with Python’s built-in map() function.

More Comprehensions!

The same list comprehension syntax can be extended to generate sets and dictionaries! By replacing brackets ([]) with curly brackets ({}), we can instantly generate an entire set. Sets are like lists, except they contain no duplicate values. Additionally, if we use curly brackets ({}) and assign a key to the value we wish to save, we can generate an entire dictionary in one line. These are officially referred to as set comprehensions and dictionary comprehensions.

Benefits and Dangers

Perhaps the largest benefit of list comprehensions in Python is their vast flexibility which allows more Pythonic code. Loops, map functions, filter functions, and reduce functions can all be reduced down to familiar and easy to read list comprehensions.

With this said, if our situation requires optimal performance or we will be handling a very large amount of data, we can compare the efficiency of list comprehensions to Python’s map, filter, and reduce functions. timeit is a great Python library for logging how long a chunk of code takes to run. If performance is less of an issue or differences in runtime are negligible, it’s generally best to choose the method that results in the cleanest and easiest to understand code.

List comprehensions are capable of handling a lot of complicated logic. Multi-line code can be reduced down into a single cleverly designed list comprehension, but for the sake of readability, this may actually be undesirable. Always remember to keep clean coding and readability at the forefront of your design decisions.

I hope you found this brief introduction to Python’s list comprehensions helpful! The best way to fully understand how they work is to start incorporating them into your own coding projects. So get out there and play with them. If anything remains unclear, I’m always more than happy to answer any questions in the comments below. Thanks for reading and as always, happy coding from Nimble Coding!