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 · Sublevel Beginner 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.

Overview

  • A comprehension builds a new collection from an existing one in a single, readable expression.
  • The pattern is [expression for item in iterable if condition].
  • Comprehensions are usually shorter and a little faster than the equivalent loop with append.
  • Square brackets make a list, braces with key: value make a dict, braces alone make a set, round brackets make a generator.
  • Keep them simple: if a comprehension needs more than one line to understand, use a loop.
  • Data cleaning and feature building often use comprehensions to transform every item.

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.

Key terms

Comprehension
A compact expression that builds a list, set or dictionary from a loop.
Filter
The optional if part that keeps only some items.
Transformation
The expression at the front that changes each item.
Generator expression
Like a list comprehension in round brackets, producing items one at a time without building a list.
Readability
How easily someone else can understand the code.
Pythonic
Written in the clear, idiomatic style the Python community prefers.

Types

Comprehensions come in several types, depending on the collection they build and whether they filter, transform or nest.

1. Basic list comprehension (mapping)

Applies an expression to every item to make a new list.

  • How it works: Python loops over the iterable, evaluates the expression for each item and collects the results in order.
  • Example: squares = [n ** 2 for n in range(1, 6)] gives [1, 4, 9, 16, 25].
  • When to use it: Use it to convert units, clean every string or compute a value for each item.

2. Filtering comprehension (with if)

Keeps only the items that pass a condition.

  • How it works: An if at the end tests each item; only items where it is True are included.
  • Example: passed = [m for m in marks if m >= 33].
  • When to use it: Use it to select rows, remove empty strings or drop invalid values.

3. Transforming with if-else

Chooses one of two expressions for each item, keeping every item.

  • How it works: The conditional expression goes before for: [a if condition else b for item in items].
  • Example: results = ["Pass" if m >= 33 else "Fail" for m in marks].
  • When to use it: Use it to label or cap values, such as replacing negatives with 0.

4. Nested comprehension

A comprehension with two or more for clauses, or a comprehension inside another.

  • How it works: The for clauses run in the same order as nested loops written out; an inner comprehension can build each row of a table.
  • Example: flat = [x for row in grid for x in row]; table = [[r * c for c in range(1, 4)] for r in range(1, 4)].
  • When to use it: Use it to flatten lists of lists or build small grids; avoid more than two levels.

5. Dictionary comprehension

Builds a dictionary with {key: value for item in iterable}.

  • How it works: Each pass produces one key-value pair; later duplicates of a key overwrite earlier ones.
  • Example: {name: len(name) for name in names}; {city: t for city, t in temps.items() if t > 35}.
  • When to use it: Use it to build lookup tables, invert a dictionary or filter one by its values.

6. Set comprehension and generator expression

{...} without colons builds a set; (...) builds a generator that yields items one at a time.

  • How it works: A set comprehension removes duplicates; a generator stores no list at all, computing each value only when asked.
  • Example: {w.lower() for w in words}; sum(m * m for m in marks) without building a list.
  • When to use it: Use sets for unique values and generators for very large data or when feeding sum(), max() and any().

Explained in detail

From a loop to one line

Many loops build a new list: start empty, loop, append. A comprehension writes that whole pattern in one expression. The loop version, squares = [] then for n in range(1, 6): squares.append(n * n), becomes squares = [n * n for n in range(1, 6)]. Read it from the middle: for each n in range(1, 6), take n * n. Adding a condition filters items: [m for m in marks if m >= 40] keeps only passing marks. Comprehensions are usually a little faster than the equivalent loop and, when short, easier to read because the purpose is stated in one place.

Four kinds

KindSyntaxExample result
List[x * 2 for x in nums][2, 4, 6]
Set{w.lower() for w in words}Unique lowercase words
Dictionary{name: len(name) for name in names}{"Riya": 4, "Arjun": 5}
Generatorsum(x * x for x in nums)A total, without building a list

Choosing between if forms

There are two different places an if can go. At the end, it filters: [m for m in marks if m >= 40] drops failing marks. At the front, as a conditional expression, it transforms every item: ["pass" if m >= 40 else "fail" for m in marks] keeps every item but labels it. Mixing these up is a common error. A filter if cannot have an else; a front if must have one.

When not to use one

  • If it needs nested loops and several conditions, write an ordinary loop.
  • If the body has side effects, such as printing or writing to a file, use a loop; comprehensions are for building values.
  • If a reader would need more than a few seconds to understand it, it is too clever.

Comprehensions are everywhere in data and AI code: building a vocabulary {word for doc in docs for word in doc.split()}, normalising features [x / max_value for x in values], or creating a grid safely [[0] * cols for _ in range(rows)], which, unlike [[0] * cols] * rows, gives every row its own list. Learning to read them fluently will make example code from libraries and tutorials much easier to follow.

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