I1 · Python Programming for AI

List and Dictionary Comprehensions

A comprehension builds a new list, set or dictionary from an existing sequence in one expression. A list comprehension has the form [expression for item in sequence if condition]; a dictionary comprehension has the form {key: value for item in sequence}.

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

Can a whole loop fit in one readable line?

A comprehension builds a new list, set or dictionary from an existing sequence in one expression. A list comprehension has the form [expression for item in sequence if condition]; a dictionary comprehension has the form {key: value for item in sequence}.

In simple words

Instead of making an empty list and appending in a loop, say what you want: [n * n for n in range(5)] means 'the square of n, for each n from 0 to 4'. Add if to filter: [n for n in marks if n >= 40] keeps only passing marks.

Why it matters

Comprehensions are the everyday Python way to transform and filter data: cleaning a list of words, scaling numbers, building a lookup table. You will see them in almost every data and AI script.

How it works

# The loop
squares = []
for n in range(5):
    squares.append(n * n)

# The same, as a comprehension
squares = [n * n for n in range(5)]

In code

Squares, a filter, cleaned words and a dictionary built in one line each.

comprehensions.py
squares = [n * n for n in range(1, 6)]
print("Squares:", squares)

marks = [35, 72, 48, 91, 20]
passed = [m for m in marks if m >= 40]
print("Passed:", passed)

raw = ["  Mango", "banana ", " GUAVA "]
clean = [fruit.strip().lower() for fruit in raw]
print("Clean:", clean)

lengths = {fruit: len(fruit) for fruit in clean}
print("Lengths:", lengths)

even_squares = {n: n * n for n in range(10) if n % 2 == 0}
print("Even squares:", even_squares)

Output

Squares: [1, 4, 9, 16, 25]
Passed: [72, 48, 91]
Clean: ['mango', 'banana', 'guava']
Lengths: {'mango': 5, 'banana': 6, 'guava': 5}
Even squares: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Try it yourself

Rewrite as a comprehension

Match each description to the comprehension that does it.

  • Double every number in nums
  • Keep only the even numbers
  • Make every word uppercase
  • Map each word to its length

Common mistakes

  • Putting the if in the wrong place. A filter goes at the end: [x for x in xs if x > 0].
  • Writing very long comprehensions that nobody can read.
  • Using a comprehension just to call a function for its side effect, such as printing. Use a loop.

Check yourself

Question 1

1. What is [n + 1 for n in [1, 2, 3]]?

Question 2

2. Where does the filter go?

Question 3

3. {w: len(w) for w in ["ai", "ml"]} is…

Summary

  • Comprehensions build lists, sets and dictionaries in one expression.
  • Add if at the end to filter.
  • Prefer a normal loop when the comprehension gets hard to read.

Finished reading?

Sources: Python docs: Data Structures