The basic comprehension

numbers = [1, 2, 3, 4]
doubled = [n * 2 for n in numbers]
print(doubled)   # [2, 4, 6, 8]

Read it left to right: take each n in numbers and put n * 2 into the new list.

Filter with an if clause

numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)   # [2, 4, 6]

An if at the end keeps only the items that match the condition — here, the even numbers.

Transform conditionally with if/else

numbers = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)   # ["odd", "even", "odd", "even"]

When you use if/else, it goes before the for because it is part of the expression that produces each value.

Which approach should you use?

  • Plain comprehension — when you map every item to a new value.
  • Comprehension with if — when you want to filter items out.
  • A normal loop — when the logic is long or has side effects; readability wins.
  • Common mistake: nesting so many clauses the line becomes unreadable.

Frequently asked questions

When should I avoid a list comprehension?

When the body needs multiple statements, error handling, or side effects. A regular for loop stays clearer in those cases.

Can I make a dictionary or set the same way?

Yes. Use {k: v for ...} for a dict comprehension and {x for ...} for a set comprehension.

Want comprehensions to click? Practise them in our free Python programming course.