Module lessons (1/4)
List comprehensions
[expr for x in iter if cond] syntax for concise transformation, filtering, and nesting.
What you'll learn in this lesson
- Replace the imperative pattern
for+.append()with compact list comprehension ([expr for x in iter]). - Distinguish the position and role of
if(trailing filter) vsif/else(leading conditional transformation). - Avoid list comprehensions that are excessively nested or used for mere side effects (
print).
Overview
A list comprehension constructs a new list by transforming and filtering an iterable into a single declarative expression. It is much more readable than a loop with .append() and is executed at C level inside the interpreter, making it slightly faster too.
The grammar reads like a sentence: [cosa_produrre for elemento in sorgente if filtro]. The single if at the end decides which elements enter, while a ternary a if cond else b before the for transforms all elements by changing value depending on the branch.
Sections covered in this lesson
- 1The mental model: trailing filter vs leading transformation
- 2Transformation, filter and inline ternary
- 3Matrix flattening and readability limits
- 4Quick check
- 5Test yourself
Unlock "List comprehensions" and the full Python Course curriculum
[expr for x in iter if cond] syntax for concise transformation, filtering, and nesting.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.