This text is part of a Real Python tutorial by James Timmins.
List comprehensions in Python provide a concise way to create lists by embedding a loop and optional conditional logic in a single line. You use a list comprehension to transform and filter elements from an iterable efficiently. It allows you to replace complex loops with more readable and often faster expressions. By understanding list comprehensions, you can optimize your code for better performance and clarity.
By the end of this lesson, you’ll understand that:
- A list comprehension in Python is a tool for creating lists by iterating over an iterable and optionally applying a condition.
- You should use list comprehensions instead of loops when you want concise, readable code that performs transformations or filtering.
- You add conditional logic to a list comprehension by including an
ifstatement within the comprehension. - A list comprehension can be faster than a
forloop because it’s optimized for performance by Python’s internal mechanisms.
In this lesson, you’ll explore how to leverage list comprehensions to simplify your code. You’ll also gain an understanding of the trade-offs that come with using them so that you can determine when other approaches are preferable.
Transforming Lists in Python
There are a few different ways to create and add items to lists in Python. In this section, you’ll explore for loops to perform these tasks. Then, you’ll move on to learn about how to use list comprehensions and when list comprehensions can benefit your Python program.
Use for Loops
The most common type of loop is the for loop. You can use a for loop to create a list of elements in three steps:
- Instantiate an empty list.
- Loop over an iterable or range of elements.
- Append each element to the end of the list.
If you want to create a list containing the first ten perfect squares, then you can complete these steps in three lines of code:
>>> squares = []
>>> for number in range(10):
... squares.append(number * number)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Here, you instantiate an empty list, squares. Then, you use a for loop to iterate over range(10). Finally, you multiply each number by itself and append the result to the end of the list.
Leverage List Comprehensions
List comprehensions are another way of making or transforming lists. With this elegant approach, you could rewrite the for loop from the first example in just a single line of code:
>>> squares = [number * number for number in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Rather than creating an empty list and adding each element to the end, you simply define the list and its contents at the same time by following this format: