Skip to content
List Comprehensions
step 1/8

Reading — step 1 of 8

Learn

~3 min readLists and Tuples

There's a pattern you've probably written a dozen times: create an empty list, loop over something, and .append() to the list each iteration. Python has a shortcut called a list comprehension that collapses the whole pattern into one expression. Once it clicks, you'll wonder how you lived without it.

The before-and-after

python

Both produce [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. The comprehension is a SINGLE expression that creates and populates the list in one step.

The structure

[ <expression>  for <var> in <iterable>  if <condition> ]

Read it as: "Build a list of <expression>, for each <var> in <iterable>, [optionally] keeping only those where <condition> is true."

Examples that progressively add features

python

Notice the order in #4 and #5: outer loop first, inner loop second — same order you'd write them as nested fors.

Set and dict comprehensions

The same pattern works for sets and dicts — just use {} and provide the right structure:

python

Generator expressions — comprehensions without the brackets

Replace [] with () and you get a generator — evaluated lazily, one item at a time, no list ever built in memory:

python

Use this for huge sequences or one-shot pipelines where you don't need the intermediate list. (You'll see this more in Python Advanced.)

When to use a comprehension — and when NOT to

Use a comprehension when:

  • The transformation/filter is simple and fits on one line.
  • The reader instantly sees what the result is.

Don't use a comprehension when:

  • The expression has side effects (printing, writing files, modifying external state). For-loops are clearer.
  • The logic spans multiple if/elif branches.
  • Nesting is more than 2 levels deep — readability tanks fast.
  • You'd need lots of explanation to follow it. A 5-line for-loop is better than a brain-melting one-liner.

Common mistakes

  • Confusing filter if with conditional if: [x for x in xs if x > 0] filters; [x if x > 0 else 0 for x in xs] substitutes. The position of if matters.
  • Trying to mutate the source: [lst.append(x) for x in items] runs .append() for side effect — bad style. Use a real for-loop.
  • Hidden complexity: a triple-nested comprehension is impressive to write and impossible to debug. Break it into for-loops if a teammate would need 30 seconds to understand it.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…