Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • write list comprehensions correctly
  • translate loop logic to comprehension form
  • use conditional filtering in comprehensions
  • avoid common syntax confusion

Basic form

[expression for item in iterable]
Example:
squares = [x * x for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

With condition

evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)

Equivalent loop

Comprehension:
squares = [x * x for x in range(1, 6)]
Equivalent loop:
squares = []
for x in range(1, 6):
    squares.append(x * x)

String-based example

chars = [ch.upper() for ch in "python"]
print(chars)

Conditional expression inside comprehension

labels = ["even" if x % 2 == 0 else "odd" for x in range(1, 6)]
print(labels)

Exam hints and traps

  • condition comes after for in filter form
  • comprehension builds a new list
  • do not confuse with generator syntax () and tuple syntax
Wrong:
# [x if x % 2 == 0 for x in range(10)]  # invalid syntax
Correct:
[x for x in range(10) if x % 2 == 0]

Quick practice

  1. Build list of cubes from 1 to 5.
  2. Build list of vowels from "education".
  3. Write loop equivalent of:
[x + 1 for x in [1, 2, 3]]

Answer key

[ch for ch in "education" if ch in "aeiou"]