Skip to main content
Module 6 · Lesson 1 of 421/36 in the course~16 min
Module lessons (1/4)

List comprehensions

Lesson preview5 hands-on exercises readyPython Course · Module 6 — Comprehensions and iteration

[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) vs if/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

  1. 1The mental model: trailing filter vs leading transformation
  2. 2Transformation, filter and inline ternary
  3. 3Matrix flattening and readability limits
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 6 — Comprehensions and iteration

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.