Nearby lessons
68 of 159Python - 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
Filtering with if
Transforming strings
Conditional expressions
A conditional expression chooses the output value, while a trailing if filters items. Keep the two forms distinct.
Nested loops
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 QuestionsProgress: 0 / 8