List, Dict & Set Comprehensions
Part of the Machine Learning 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.
Comprehensions build a new list, dictionary or set from another collection in one readable line, often with a filter. They are everywhere in data cleaning and feature code.

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]
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
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
Quick check
What does [n for n in [4, 7, 10] if n % 2 == 0] return?
Go deeper
- 1Rewrite three for-loops from your old code as list comprehensions.
- 2Build a dict comprehension that maps each word in a sentence to its length.
- 3Know when to stop: if a comprehension needs two conditions and nesting, use a normal loop.
Also part of these roadmaps
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.