Python Tutorial: List Comprehensions
Build lists in one line. The most Pythonic feature — write less, do more.
What you'll learn in this Python list comprehensions tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 14 minutes.
- The old way vs the Python way — Want to double every number in a list? Here's the traditional way — a loop, an empty list, and an append.
- Your first list comprehension — Same result, one line:
- Filtering with if — Add `if` at the end to filter: `[x for x in list if condition]`
- Transform + filter together — You can transform AND filter in one comprehension.
- Strings work too — Comprehensions work on any iterable — including strings.
- Dictionary comprehensions — Same idea, but with `{key: value for ...}` — builds a dict instead of a list.
- Set comprehensions — Use `{expression for ...}` (no colon) for a set — a collection with no duplicates.
- Build a grade filter 🎓 — Given a dict of student scores, use comprehensions to: