Hello! In our last lesson, we worked with for and while loops to repeat actions and if/elif/else statements to make decisions. You saw how these structures are often used together to build a new list by iterating over an existing one and appending elements that meet certain criteria. Today, we'll build directly on that foundation.
This lesson introduces list comprehensions, a powerful and widely-used Python feature. You will learn how to rewrite a common type of for loop into a single, elegant line of code. This is a hallmark of "Pythonic" programming—writing code that is not only effective but also concise and readable. Mastering this will help you write cleaner code as you progress towards building complex logic in your FastAPI applications.
From For Loop to List Comprehension
At its core, a list comprehension is a more compact syntax for a specific kind of for loop: one that creates a new list. Let's start with a visual comparison.
Consider this common pattern using a for loop:
- Create an empty list.
- Loop over an existing iterable (like another list or a range).
- Inside the loop, perform some operation.
- Append the result to the new list.
The video below provides an excellent visual walkthrough of how this multi-line process is condensed into a single list comprehension.
List Comprehensions - Visually Explained
This video from the "Visually Explained" channel breaks down the syntax of a list comprehension by directly comparing it to an equivalent for loop.
Please watch the segment from the introduction to the first main example, "From Loop to Comprehension". Pay close attention to how the pieces of the for loop are rearranged to form the comprehension.
As you saw, the list comprehension takes the essential parts of the loop—the transformation and the iteration—and arranges them inside square brackets. This eliminates the need for initializing an empty list and making explicit calls to .append().
The Anatomy of a List Comprehension
A list comprehension consists of up to three main parts, which are easiest to read from left to right but are often constructed from right to left.

Let's break these down:
- Expression:
item * 2— What to do with each item before adding it to the new list. This is the "transformation". forclause:for item in original_list— The loop itself, which iterates over the source iterable.ifclause (optional):if item % 2 == 0— A filter that includes only the items for which the condition isTrue.
The following image provides a direct, code-vs-code comparison of this exact structure.

To see this in action with a variety of practical examples, the next video is very helpful. It moves quickly but demonstrates how to apply transformations and filters to numbers and strings.
Learn Python LIST COMPREHENSIONS in 10 minutes! 📃
This video by "Bro Code" is a rapid-fire tutorial showing how to construct list comprehensions for various tasks.
Watch these two key segments: First, see the basic syntax in action from the beginning. Next, focus on how to add conditional logic. The examples on filtering numbers and grades are particularly useful. Watch from "Working with conditions" to the end of the examples.
With the visual and video introductions complete, let's solidify this with a detailed textual explanation. The following article from the "Pydon't" blog provides an excellent breakdown.
List comprehensions 101 | Pydon't 🐍
This article clearly explains how to convert for loops into list comprehensions, including those with conditional if statements.
Please read the following two sections: Start at the beginning and continue through the section "A loop that builds a list". This reinforces the direct parallel between the two syntaxes. Next, read the section on filtering data. It shows how to add an if condition and makes an important point about formatting longer comprehensions across multiple lines for readability.
Why and When to Use List Comprehensions
While you can use list comprehensions to replace many for loops, it doesn't mean you always should. Their primary benefit is improving readability and conciseness for simple tasks. For complex logic, a traditional for loop is often clearer.
List comprehensions are ideal for:
- Creating a new list where each element is a transformation of an element from another list (e.g., squaring all numbers).
- Creating a sub-list that contains only the elements from another list that satisfy a condition (e.g., filtering for even numbers).
- Doing both at the same time.
They are not suitable for:
- Loops where you don't need to create a list (e.g., just printing items).
- Loops with complex logic involving
eliforelseblocks. - Loops that need to perform actions that have side effects (e.g., modifying another variable or writing to a file). A comprehension's job is only to produce a new list.
The article you just looked at has excellent sections on this. It's worth spending a few more minutes to understand the best practices.
List comprehensions 101 | Pydon't 🐍
This part of the article discusses the advantages of list comprehensions and, crucially, when to use them and when to stick with a for loop.
Please read the following sections to understand the proper use cases: Advantages: This covers speed, conciseness, and readability. Good use cases: These examples show appropriate and common patterns. Bad use cases: This is very important. Pay close attention to the examples of what not to do, especially regarding side effects.
Finally, while readability is key, it's also worth noting that list comprehensions are often faster than the equivalent for loop because the iteration is handled at a lower level in Python's C implementation. The "Visually Explained" video has a great segment on this trade-off.
List Comprehensions - Visually Explained
This final clip discusses the performance benefits and offers guidance on when to prioritize readability over a complex, hard-to-read comprehension.
Watch the segment on performance and readability.
Conclusion
You have now learned one of Python's most expressive features. List comprehensions allow you to take the looping and conditional logic from our previous lesson and apply it in a more compact and often more readable format. Using them effectively is a sign of a proficient Python developer.
Key Takeaways:
- List comprehensions provide a concise syntax for creating lists from iterables.
- The full syntax is
[expression for item in iterable if condition], where theifpart is optional. - They are best used for straightforward transformations and filtering, where they improve code readability.
- For complex logic or loops that don't produce a list, a standard
forloop remains the better choice. - List comprehensions should be "pure"—their only job is to create a new list, not to produce side effects.
In our next lesson, we will cover functions. Functions are the primary way we organize code into logical, reusable blocks. The loops, conditionals, and list comprehensions you've learned are the building blocks of the logic that you'll soon be packaging inside your own custom functions.