HomeCourseModule 04 › List comprehensions — one-line loops

List comprehensions — one-line loops

Module 04 · Control Flow7 min readBeginner

What you'll learn

  • Read a list comprehension
  • Convert a for-loop to a comprehension
  • Add a filter (if-clause) to a comprehension

The pattern

# Long form
squares = []
for n in range(10):
    squares.append(n * n)

# Comprehension — same result
squares = [n * n for n in range(10)]

Read it left to right: "a list of n * n for every n in range(10)."

With a filter

evens = [n for n in range(20) if n % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Transform + filter

names = ["alice", "bob", "carol", "dave"]
short_upper = [n.upper() for n in names if len(n) < 5]
# ['ALICE', 'BOB', 'DAVE']

Dict and set comprehensions

# dict
prices = {"a": 1, "b": 2, "c": 3}
doubled = {k: v * 2 for k, v in prices.items()}
# {'a': 2, 'b': 4, 'c': 6}

# set (no duplicates)
words = ["apple", "ant", "banana"]
first_letters = {w[0] for w in words}
# {'a', 'b'}
💡 When to use them
Use a comprehension when the loop body is one short transformation. If you're doing five things to each item, use a regular for-loop — comprehensions stop helping when they get long.

Key takeaways

  • [expression for item in collection] = one-line list builder.
  • Add if condition at the end to filter.
  • Also works for dicts and sets.
  • Don't overuse — readability beats brevity.

Three quick conversions

Convert each loop to a list comprehension.

# 1
result = []
for n in range(20):
    if n % 3 == 0:
        result.append(n)

# 2
upper_names = []
for name in ["alice", "bob"]:
    upper_names.append(name.upper())

# 3
totals = []
for r in [{"qty":3,"price":10}, {"qty":2,"price":15}]:
    totals.append(r["qty"] * r["price"])
📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.