Stop 01 · Programming & CS FoundationsTopics · 5/12

List/Dict/Set Comprehensions

Part of the AI Engineer Roadmap

In short

Comprehensions turn a four-line loop into one readable line. You'll see them in almost every preprocessing script, so learning to read and write them pays off quickly.

Pythonic one-line syntax for building lists, dicts and sets from iterables — used everywhere in data preprocessing to keep code short and fast.

The purple blob picks only the ripe yellow mangoes from a fruit cart into a basket.

Think of it like this

Picking ripe mangoes at the thela

You don't write down every mango and then decide. You run your hand over the crate, pick only the soft yellow ones and drop them straight into your basket. A comprehension does that in one go: look at each item, keep the ones you want, maybe change them, collect.

Watch it happen

[x * 2 for x in nums if x > 6]

3
0
x
8
1
5
2
12
3
7
4
10
5

1/5Python walks through nums from left to right. 3 fails x > 6, so it's skipped.

The big ideas

What you need to know

List: [expr for x in items]

Builds a new list. Read it as 'give me expr, for each x in items'.

Add if to filter

[x for x in rows if x is not None] keeps only real values. The if goes at the end.

Dict: {k: v for ...}

{name: len(name) for name in names} builds a lookup table in one line. Great for label-to-id mappings.

Set: {x for ...}

Same as a list comprehension with curly braces, but duplicates are removed automatically.

See it in code

Walk through the code

python
1reviews = ["  Great product ", "BAD", "", "okay ", "great product"]2 3cleaned = [r.strip().lower() for r in reviews if r.strip()]4# ['great product', 'bad', 'okay', 'great product']5 6unique = {r for r in cleaned}7# {'great product', 'bad', 'okay'}8 9labels = sorted(unique)10label_to_id = {label: i for i, label in enumerate(labels)}11# {'bad': 0, 'great product': 1, 'okay': 2}

1/3Strip spaces, lowercase, and drop empty strings with the if at the end.

Three comprehensions turn messy reviews into a clean label-to-id mapping, the same kind of mapping you need before training a text classifier.

Save yourself the pain

Common mistakes

Oops

Cramming two loops and three conditions into one comprehension nobody can read.

Do this instead

If it doesn't fit comfortably on one line, write a normal for loop. Clear beats clever.

Oops

Using a list comprehension just for side effects, like [print(x) for x in items].

Do this instead

Use a plain for loop when you aren't building a new collection.

Your mission

Rewrite loops as comprehensions

~15 min

Quick check

What does [n for n in [4, 7, 10] if n % 2 == 0] return?

Go deeper

  1. 1Convert 10 verbose for-loops into comprehensions as a drill.
  2. 2Practice nested comprehensions and comprehensions with conditionals.
  3. 3Learn when a comprehension hurts readability and a plain loop is clearer.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge