A Beginner’s Guide to Python List Comprehensions

Eliminate 90% of your for loops

A Beginner’s Guide to Python List Comprehensions
Photo by NeONBRAND on Unsplash

Every programming language has its own strengths and features. One of the most iconic features of Python are list comprehensions. Comprehensions are fast, easy to read, and able to be used by beginners through experts.

List comprehensions are a shorthand technique for creating a new list that allows both for loops and if statements to control the contents of the newly created list.

Benefits of Comprehensions

There are three primary benefits of using list comprehensions in Python.

  1. Simplicity: List comprehensions eliminate for loops, making your code easier to read. Other languages such as JavaScript use array methods named .map() and .filter() to achieve the same results, but these techniques are more confusing for beginners.
  2. Speed: List comprehensions are even faster than the for loops that they are replacing. If you want to refactor some of your code for performance, replacing loops with comprehensions is low-hanging fruit.
  3. Functional Programming Principles: This isn’t as important for beginners, but functional programming is a conceptual framework where mutable data is not changed. Since list comprehensions create a new list and leave existing data unmodified, it adheres to functional programming principles.

Creating Our First List Comprehension

Every list comprehension is going to take place within square brackets and will involve a for loop. What happens is the list will be created from each item in the for loop, which can be modified as needed.

Our first example will have no modifications and will create a list of integers 1–5 by iterating over the range() function.nums = [n for n in range(1,6)]
print(nums) # [1, 2, 3, 4, 5]

In the example, each value of the range is assigned to n one at a time. We return each value unmodified to our new list — this is the n before the for loop.

Remember, the iterable in the for loop does not have to be a range() function. It can be any iterable value.

List Comprehension with Modification

Now we’re going to take it up a level and modify each value in our for loop to comprehend a new list.nums = [1,2,3,4,5]
squares = [n*n for n in nums]
print(squares) # [1, 4, 9, 16, 25]

In this example we make two changes from the previous code. First, we use an already defined list in the for loop. Second, what we return to the list comprehension is the square of each value.

List Comprehension With Filtering

Continuing to build on our examples, this time we’ll add a condition for each value to pass before being included in our new list.nums = [1,2,3,4,5]
odd_squares = [n*n for n in nums if n%2 == 1]
print(odd_squares) # [1, 9, 25]

The if statement goes after the for loop — this is critical because the order matters.

List Comprehension With Nested For Loop

The last example we will show demonstrates a list comprehension with nested for loops. This does not build on the previous code.matrix = [[x for x in range(1,4)] for y in range(1,4)]
print(matrix) # [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

At this point you may be thinking that the comprehension is getting a bit cluttered. We agree. To improve the readability of this comprehension, let’s spread it out over multiple lines.matrix = [
 [x for x in range(1,4)]
 for y in range(1,4)
]
print(matrix) # [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Let’s do one last example. This time we’ll be creating a list of birthdays from a list of dictionaries. We’ll have to use all the techniques previously covered in one single list comprehension.people = [{
 "first_name": "Mata",
 "last_name": "Rosendall",
 "birthday": "9/25/1984"
}, {
 "first_name": "Sandra",
 "last_name": "O'Gaven",
 "birthday": "8/21/1995"
}]birthdays = [
 person[term]
 for person in people
 for term in person
 if term == "birthday"
]print(birthdays) # ['9/25/1984', '8/21/1995']

In this example, we iterate over people, assigning each dictionary to person. Then, we iterate over each identifier in the dictionary assigning each key to term. If the value of term is equal to "birthday", then the value of person[term] is included in the list comprehension.


You’re ready to go out in the wild and build some awesome list comprehensions. Your effort will be rewarded with faster, more readable code. Win win.

Start by refactoring your old code and remove those for loops. You’ll be surprised and may even end up with a script that has zero 😱.


Thanks for reading this article. Please post your experiences, questions, and feedback below.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe