Course contentsShow
← Python
Lesson 94 of 1,0602. Control Flow and LogicFree lesson

Transforming Iterables with List Comprehensions

Learners will be able to condense simple loop logic into a single, readable line of code to generate new lists.

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

  1. n * n: This is the "expression." It tells Python what to do to each item.
  2. for n in numbers: This is the familiar loop part, telling Python where to get the items.
  3. []: 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.