Nearby lessons

68 of 159

Python - List Comprehensions

📌 What You Will Learn
  • Explain the structure of a list comprehension
  • Transform values with an expression
  • Filter values with an if condition
  • Use conditional expressions and nested loops
  • Rewrite simple loops as comprehensions safely

What is a list comprehension?

A list comprehension is a compact way to build a list from an iterable. Its general form is [expression for item in iterable].

Basic example

🐍Code Cell
1squares = [number ** 2 for number in range(1, 5)]
2print(squares)
Output
[1, 4, 9, 16]

Filtering with if

🐍Code Cell
1evens = [number for number in range(10) if number % 2 == 0]
2print(evens)
Output
[0, 2, 4, 6, 8]

Transforming strings

🐍Code Cell
1words = ['python', 'web']
2upper_words = [word.upper() for word in words]
3print(upper_words)
Output
['PYTHON', 'WEB']

Conditional expressions

A conditional expression chooses the output value, while a trailing if filters items. Keep the two forms distinct.

🐍Code Cell
1labels = ['even' if n % 2 == 0 else 'odd' for n in range(4)]
2print(labels)
Output
['even', 'odd', 'even', 'odd']

Nested loops

🐍Code Cell
1pairs = [(x, y) for x in [1, 2] for y in ['a', 'b']]
2print(pairs)
Output
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Set and dictionary comprehensions

The same idea supports sets with {expression for item in iterable} and dictionaries with {key: value for item in iterable}.

When a loop is better

Use a regular loop when you need multiple statements, error handling, side effects, or deeply nested conditions. Readability is more important than minimizing lines.

📝 Key Takeaways
  • A comprehension contains an expression followed by a for clause
  • An if clause filters values
  • Comprehensions return a new list and do not mutate the source by default
  • Nested comprehensions should remain readable
  • A normal loop is preferable when logic becomes complex

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8