List Comprehensions
In this tutorial, we'll build new lists from existing values.
A list comprehension is a compact way to build a new list from existing values.
Normal loop:
numbers = [1, 2, 3]
doubled = []
for number in numbers:
doubled.append(number * 2)
List comprehension:
numbers = [1, 2, 3]
doubled = [number * 2 for number in numbers]
Both create:
[2, 4, 6]
The Shape
[expression for item in collection]
The expression says what to put in the new list.
The for part says where the values come from.
More Examples
names = ["ada", "grace", "linus"]
capitalized = [name.capitalize() for name in names]
prices = [10, 20, 30]
with_tax = [price * 1.2 for price in prices]
When to Use Them
Use a list comprehension when you are building a list in a simple, readable way.
If the logic takes several steps, a normal loop is often better.
Compare Both Versions
When learning, it helps to write the normal loop first:
lengths = []
for name in names:
lengths.append(len(name))
Then rewrite it:
lengths = [len(name) for name in names]
This makes the comprehension feel less mysterious.
Practice
Start with numbers = [1, 2, 3, 4]. Use a list comprehension to create a list of their squares.