Skip to main content

List Comprehensions — Transforming Data

You've mastered creating, modifying, and sorting lists. Now comes one of Python's most elegant features: list comprehensions. They transform lists in a single line that reads almost like English: "a list of X for each Y in Z, if condition."

In professional Python code, comprehensions appear everywhere. They're concise, readable (when written well), and often faster than traditional loops. But here's the key insight: clarity trumps cleverness. A 5-line loop that's easy to understand beats a 1-line comprehension that makes your teammates pause.

Let's learn how to write them, when to use them, and—critically—when a regular loop is the better choice.

From Loops to Comprehensions: The Transformation

You already know how to transform data with loops:

Loading Python environment...

This is clear and explicit: create an empty list, iterate over numbers, append each squared value. But Python offers a shorter way to express this exact idea:

Loading Python environment...

Both produce identical results. The second is a list comprehension—a syntactic shortcut for creating a new list by transforming an existing one.

💬 AI Colearning Prompt

"Explain the mental transformation from a for-loop with append() to a list comprehension. What parts of the loop map to what parts of the comprehension syntax?"

This helps you see the structural connection so comprehensions don't feel magical.

Understanding Comprehension Syntax

A list comprehension has three essential parts:

[expression   for   item   in   iterable]
^1 ^2 ^3 ^4 ^5
  1. Expression — What gets added to the new list (e.g., x ** 2)
  2. for keyword — Signals iteration starts
  3. Iteration variable — Holds one item at a time (e.g., x)
  4. in keyword — Connects to the source
  5. Iterable — The source to iterate over (e.g., numbers)

Let's trace through an example:

Loading Python environment...

Execution:

  • Iteration 1: x = 1 → expression 1 ** 2 = 1 → add to result
  • Iteration 2: x = 2 → expression 2 ** 2 = 4 → add to result
  • Iteration 3: x = 3 → expression 3 ** 2 = 9 → add to result
  • And so on...

Result: [1, 4, 9, 16, 25]

Notice: the expression runs for each item in the iterable, and the result of each expression becomes an element in the new list.

🎓 Expert Insight

In AI-native development, you don't memorize the syntax—you understand the intent: "I want to transform each item from a source list." The syntax is just Python's way of expressing that idea concisely. When syntax feels confusing, ask AI: "Break down this comprehension step-by-step."

Exercise 1: Writing Simple Comprehensions

Write a comprehension for each transformation. Check your type hints.

  1. Double each number: [2, 4, 6, 8, 10] from [1, 2, 3, 4, 5]
  2. Extract first letters: ['a', 'b', 'c'] from ['apple', 'banana', 'cherry']
  3. Convert to uppercase: ['HELLO', 'WORLD'] from ['hello', 'world']

Your turn — try these before looking at the solutions:

Loading Python environment...

Adding Conditions: Filtering with if

Now for a powerful variation: filtering. Add an if condition to include only items that match:

[expression   for   item   in   iterable   if   condition]

Example — keep only even numbers:

Loading Python environment...

The if condition acts as a gate: items that pass the condition are included; others are filtered out.

Execution:

  • n = 1: 1 % 2 == 0? No → skip
  • n = 2: 2 % 2 == 0? Yes → include 2
  • n = 3: 3 % 2 == 0? No → skip
  • n = 4: 4 % 2 == 0? Yes → include 4
  • And so on...

Result: [2, 4, 6, 8, 10]

Key insight: The condition evaluates before the expression is added. If the condition is false, that item is skipped entirely.

🚀 CoLearning Challenge

Ask your AI Co-Teacher:

"I have a list of words. Write a comprehension that keeps only words that start with a vowel. Then explain the condition you used and how it filters the list."

Expected Outcome: You understand how to write string conditions in comprehensions and see how the if gate works conceptually.

Exercise 2: Filtering with Comprehensions

  1. Keep numbers greater than 5: From [2, 5, 7, 1, 9, 3], get [7, 9]
  2. Keep strings longer than 3 characters: From ['it', 'hello', 'ok', 'python'], get ['hello', 'python']
  3. Keep only positive numbers: From [-5, 3, -1, 8, -2, 0, 6], get [3, 8, 6]

Loading Python environment...

✨ Teaching Tip

When your comprehension gets hard to read (many characters, complex condition), use Claude Code to split it into a traditional loop. Ask: "Make this comprehension into a for-loop that's easier to understand." Your AI will refactor it, and you can choose whichever version is clearer for your team.

Combining Expression and Filtering

You can transform and filter in one comprehension:

Loading Python environment...

Order matters: the if condition filters first, then the expression is applied to remaining items.

Execution:

  • Filter: keep [2, 4, 6, 8, 10]
  • Transform: apply * 2[4, 8, 12, 16, 20]

This is very Pythonic and concise. But remember: clarity is king. If this makes someone pause during code review, consider splitting it:

Loading Python environment...

Both are correct. The second is just more readable and easier to test independently.

Exercise 3: Transform and Filter

  1. Square only odd numbers: From [1, 2, 3, 4, 5], get [1, 9, 25]
  2. Uppercase only words longer than 4 characters: From ['hi', 'hello', 'hey', 'python'], get ['HELLO', 'PYTHON']

Loading Python environment...

A Word on Readability: Clarity Trumps Cleverness

Comprehensions are beautiful when they're simple. But Python developers sometimes get carried away:

Loading Python environment...

This is syntactically correct but difficult to understand at a glance. It combines:

  • Nested loops (a comprehension inside another comprehension)
  • Multiple conditions
  • Complex expressions

Professional approach: When you can't read your comprehension in one breath, refactor to a loop.

Loading Python environment...

This is longer but tells the story clearly: "For each number in data, if it's even, create a list of doubled values from 0 to that number."

Rule of thumb:

  • Simple comprehension (single line, easy to read): Use it
  • Complex comprehension (nested loops, multiple conditions): Use a traditional loop instead
  • When in doubt: Ask your AI and your team. A 4-line loop beats a 1-line mystery.

💬 AI Colearning Prompt

"Is this comprehension readable? [str(x*2) for x in range(10) if x % 3 == 0 and x > 2] If not, rewrite it as a for-loop and explain why the loop is clearer."

Brief Introduction to Nested Comprehensions

For completeness: you can put a comprehension inside another comprehension. But we're not diving deep here—focus on simple, readable comprehensions first.

Loading Python environment...

Both create:

[[1, 2, 3],
[2, 4, 6],
[3, 6, 9]]

The traditional loop is much clearer. Use it.

Key lesson: Nested comprehensions exist, but they're often harder to debug and maintain. Master simple comprehensions first. Save nested ones for cases where the intent is crystal clear (rare).


Try With AI

Master list comprehensions and learn when to use them vs. traditional loops.

🔍 Explore Comprehension Patterns:

"Show me comprehension syntax with examples: filter-only ([x for x in items if condition]), transform-only ([x*2 for x in items]), and filter+transform. Explain when each pattern applies."

🎯 Practice Loop Conversion:

"Help me convert these loops to comprehensions: square even numbers from 1-10, extract first letters from names, uppercase words longer than 4 chars. Show both versions and explain readability."

🧪 Test Readability Limits:

"Debug this nested comprehension: [[x*y for x in range(1,6) if x%2==0] for y in range(1,4) if y!=2]. Explain what it does, why it's hard to read, rewrite as clear loops. Give me a rule for when NOT to use comprehensions."

🚀 Apply to Data Pipeline:

"Build grade processor: filter scores >= 60 from [95, 67, 88, 72, 55, 91, 100, 45, 80], convert to letter grades (A/B/C/D). Use comprehension for filter, loop for grading. Explain when to mix approaches."