IntermediateLesson firstCategory 7 of 20

List Comprehensions

Write concise list transformations. Read the lesson first, then move through the exercises in order.

8 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Standardizing Input

Study Material

Read the full lesson

What a list comprehension is

A list comprehension is a short way to build a new list from an existing one. It is often clearer than a long loop when the logic is simple.

The basic pattern

python
squares = [x ** 2 for x in range(1, 6)] print(squares)

This means: take each number, square it, and collect the results in a new list.

Filtering with an if condition

You can keep only the items that pass a test.

python
nums = [1, 2, 3, 4, 5, 6] evens = [x for x in nums if x % 2 == 0] print(evens)

Transforming text

Comprehensions work with strings too.

python
word = "python is fun" vowels = [ch for ch in word if ch in "aeiou"] print(vowels)

Nested comprehensions (flattening)

You can flatten a list of lists in one line.

python
matrix = [[1, 2], [3, 4]] flat = [num for row in matrix for num in row] print(flat)

When not to use a comprehension

If the logic is complex or hard to read, use a normal loop. Clarity is more important than short code.

Common mistakes to avoid

  • Forgetting the order: for row in matrix for num in row is different from the other way around.
  • Trying to use a comprehension for side effects like printing.
  • Making a comprehension so long that it is hard to understand.

What you should understand after this lesson

  • The basic comprehension pattern.
  • How to filter items with if.
  • How to build new lists from existing data quickly.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.