Transforming Iterables with List Comprehensions
In this lesson, you will learn how to condense multi-line loop logic into a single, elegant line of code to create new lists.
The Old Way: Building Lists
Up until now, when you wanted to create a new list by transforming items from an existing one, you likely used a for loop. For example, if you wanted to square every number in a list, you would write:
numbers = [1, 2, 3, 4]
squares = []
for n in numbers:
squares.append(n * n)
# squares is now [1, 4, 9, 16]
This approach is clear, but it takes three lines of code just to perform a simple transformation.
The New Way: List Comprehensions
Python provides a shorthand called a list comprehension. This allows you to perform the loop and the list creation simultaneously within a single pair of square brackets. The syntax follows this pattern: [expression for item in iterable].
Here is how that same squaring operation looks using a list comprehension:
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]
How it Works
n * n: This is the "expression." It tells Python what to do to each item.for n in numbers: This is the familiar loop part, telling Python where to get the items.[]: The surrounding brackets tell Python to collect all the results into a new list immediately.
You can think of this as reading the code from left to right: "Create a list where I take every n in numbers and transform it by calculating n * n."
This tool is not just shorter; it is often faster for the computer to execute and is considered standard "Pythonic" style for simple transformations. Whenever you find yourself initializing an empty list and immediately filling it with a simple for loop, a list comprehension is almost certainly the cleaner choice.
Key Takeaway: List comprehensions allow you to condense loop-based list creation into a single, readable line using the [expression for item in iterable] syntax.