List Comprehensions#

Learning Objectives

Questions:

  • How can I write lists more concisely in Python?

  • How do list comprehensions compare to regular for loops?

Objectives:

  • Understand the basic syntax of a list comprehension.

  • Transform a simple for loop into an equivalent list comprehension.

  • Apply conditional filtering within a list comprehension.


What are list comprehensions?#

In Python, a list comprehension is a compact way to build a new list from existing data.
Instead of writing a multi-line for loop and calling .append() for each element, you can express the same idea in a single, readable line.

List comprehensions can make your programs shorter, easier to read, and sometimes faster.
But remember: clarity beats cleverness. If a comprehension starts to feel crowded or hard to read, use a regular loop.


Start from a for loop#

Because you already know for loops, let us begin there and then convert to a list comprehension.

Imagine you want to create a list of squares for the numbers 0 through 9:

squares = []
for x in range(10):
    squares.append(x**2)

squares

Hide code cell output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The comprehension version would look like this (same result):

squares = [x**2 for x in range(10)]
squares

Hide code cell output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Both approaches do the same thing: iterate → transform → collect.
The comprehension just expresses it more compactly.


The syntax of a list comprehension#

The general pattern of a list comprehension looks like this:

[ expression for item in iterable if condition ]
  • expression → what you put into the new list (often a transformation of item).

  • for item in iterable → the loop that goes through each item in your source data.

  • if condition (optional) → a filter deciding whether to include the current item.

Think of a list comprehension as a compressed for loop with an optional filter.

Reading and writing comprehensions step by step#

Start with the loop you would normally write, then compress it:

  1. Write the loop that visits each element.

  2. (Optional) Add a condition to filter elements.

  3. Move the “result expression” (what you would .append()) to the front.

Loop → comprehension (even squares 0–9):

# loop
even_squares = []
for x in range(10):
    if x % 2 == 0:
        even_squares.append(x**2)

even_squares

Hide code cell output

[0, 4, 16, 36, 64]
# comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]

even_squares

Hide code cell output

[0, 4, 16, 36, 64]

The two code blocks above do exactly the same thing: they both build a list of the squares of the even numbers from 0 to 9.

  • In the loop version, we create an empty list, loop over numbers, check if each number is even, and then append its square to the list.

  • In the comprehension version, the same logic is expressed in a single line: iterate through the numbers, filter with if x % 2 == 0, and apply the expression x**2.

The comprehension is simply a more compact way to write the loop.

Understanding the order of execution in list comprehensions#

Although the code is written as:

[x**2 for x in range(10) if x % 2 == 0]

Hide code cell output

[0, 4, 16, 36, 64]

The way it executes mirrors a normal for loop:

  1. Loop through numbers 0 to 9 (for x in range(10)).

  2. Check the condition if x % 2 == 0 - keep only the even numbers.

  3. Apply the expression x**2 to each number that passed the test.

So even though the expression appears first in the code, the execution order is: loop → condition → expression.

Tip: If the order feels confusing, rewrite the comprehension as a loop with .append() and compare - they are equivalent.


Examples#

Transforming values#

A comprehension can transform each element on the way in:

words = ["python", "list", "comprehension"]
uppercased = [w.upper() for w in words]
uppercased

Hide code cell output

['PYTHON', 'LIST', 'COMPREHENSION']

Filtering elements#

You can include only certain items by adding an if clause:

evens = [n for n in range(10) if n % 2 == 0]
evens

Hide code cell output

[0, 2, 4, 6, 8]

Combine transform + filter:

even_squares = [n**2 for n in range(10) if n % 2 == 0]
even_squares

Hide code cell output

[0, 4, 16, 36, 64]

Nested comprehensions (use with care)#

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
flattened

Hide code cell output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Nested comprehensions can be harder to read. If a comprehension feels hard to read, it is often better to write a regular loop.


Exercises#


Exercise 1: Odd numbers#

Create a list of the first 20 odd numbers using a list comprehension.

Exercise 2: Normalise names#

Given names = ["alice", "Bob", "CHARLIE"], use list comprehension to build a new list where all names are lowercase.

Exercise 3: Filter positives#

From numbers = [3, -1, 4, -2, 5, -6], use list comprehension to make a list containing only the positive values.

Exercise 4: Filter and transform#

Use list comprehension to produce the squares of all numbers from 0–30 that are divisible by 3.

Exercise 5: Two-letter combinations#

Use list comprehension to create all two-letter combinations from "AB" and "CD" to get ["AC", "AD", "BC", "BD"].

Exercise 6: Word lengths#

From the sentence "List comprehensions are powerful", use list comprehension to make a list of word lengths.

Exercise 7: Loop to comprehension#

Rewrite this loop as a list comprehension:

result = []
for x in range(20):
    if x % 5 == 0:
        result.append(x // 5)

Key Points#

  • List comprehensions are a quick way to build lists.

  • General syntax: [expression for item in iterable if condition].

  • They work like loops: go through items, check condition, add result.

  • Good for simple transform or filter but use loops if it gets too complex.