List Comprehensions
List comprehensions are a hallmark of idiomatic Python. They provide a concise, readable, and efficient way to create lists. Once you’re comfortable with them, you’ll see them everywhere and use them often.
1. The Anatomy of a List Comprehension
At its core, a list comprehension is a syntactic shortcut for a for
loop that builds a list.
The basic syntax is: [expression for item in iterable]
expression
: The operation to perform on eachitem
to create the new element.for item in iterable
: A standardfor
loop that iterates over a sequence.
The concise, preferred way.
Pyground
Create a list of the squares of the numbers from 0 to 9.
Expected Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Output:
2. Adding Conditional Logic
Comprehensions become even more powerful when you add conditional logic. There are two ways to do this, and they serve different purposes.
Filtering Items with if
To filter the iterable and only include items that meet a certain condition, add an if
clause at the end.
Syntax: [expression for item in iterable if condition]
Pyground
From a list of numbers, create a new list containing only the even numbers.
Expected Output:
[2, 4, 6, 8, 10]
Output:
Key Difference:
if
at the end filters out items.if/else
in the expression transforms every item.
3. Nested Comprehensions
You can nest for
loops inside a comprehension to work with nested data structures, like creating a matrix or flattening a list of lists. The loops are written in the same order as they would be in a standard nested for
loop.
Pyground
Create a flattened list of all numbers from a list of lists.
Expected Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
4. Beyond Lists: Set and Dictionary Comprehensions
The same powerful syntax can be used to create sets and dictionaries.
Use curly braces {}
instead of square brackets []
to create a set. This is useful for creating a collection of unique items.
Pyground
Create a set of unique lowercase first letters from a list of names.
Expected Output:
{'a', 'b', 'c'}
Output:
Why Use Comprehensions?
- Concise & Readable: They express the intent of building a collection in a single, clear line of code.
- Expressive: They handle filtering and mapping in a very natural way.
- Performant: They are often faster than creating an empty list and repeatedly calling
.append()
in afor
loop.