Mastering Python List Comprehensions
Basic Comprehension Syntax
From Loop to Comprehension
You're likely familiar with building a new list from an existing one using a for loop. It’s a standard pattern in programming: initialize an empty list, loop through an iterable, perform an operation on each item, and append the result. It works perfectly, but it's a bit verbose for such a common task.
# The classic for-loop approach
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
print(squares) # Output: [1, 4, 9, 16, 25]
This three-line structure is clear but can be condensed. Python offers a more elegant and efficient way to achieve the same result in a single line: a list comprehension. It’s a powerful feature that makes your code more “Pythonic” — that is, concise and readable.
List comprehension is an elegant way to define and create lists in Python.
A list comprehension essentially flips the for loop's structure. Instead of putting the action inside the loop, you put it at the beginning. The core syntax is [expression for item in iterable].
expression: What to do with each item.for item in iterable: The loop itself.
Let’s refactor our previous example into a list comprehension. Notice how the n * n (the expression) comes first, followed by the for n in numbers loop.
# The list comprehension approach
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
Mapping Values
This process of transforming each element from an input collection into a new element in an output collection is often called mapping. A list comprehension is a perfect tool for mapping. Every item in the original numbers list is mapped to a new value (its square) in the squares list.
This isn't limited to numbers. You can perform any operation that constitutes a valid Python expression. An expression is any piece of code that evaluates to a value, like n * n or name.upper(). This is different from a statement, like print(name), which performs an action but doesn't produce a value to be stored.
Here's another example, this time mapping a list of strings to their uppercase versions.
names = ['alice', 'bob', 'charlie']
uppercase_names = [name.upper() for name in names]
print(uppercase_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
This is much cleaner than the equivalent for loop.
names = ['alice', 'bob', 'charlie']
uppercase_names = []
for name in names:
uppercase_names.append(name.upper())
print(uppercase_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
The pattern is the same: take an input iterable, define an expression to apply to each item, and create a new list with the results. Once you get used to the syntax, it becomes a powerful tool for writing clean, efficient code.
Ready to test your knowledge?
What is the primary benefit of using a Python list comprehension compared to a traditional for loop for creating a new list?
Given a list numbers = [10, 20, 30], which code snippet correctly creates a new list halved_numbers where each element is half of the original?
Now you can see how a simple loop can be transformed into a more concise and readable single line of code. Next, we'll explore how to add conditional logic to make your comprehensions even more powerful.