Lesson 4 of 4Module 1 · 0% of course
Python Foundations · Names & data

Comprehensions, iterators & generators

Build lists in one readable line, and stream big files without loading them into memory.

15 min · 5 steps · videoJump to quiz ↓
Talks - Reuven M. Lerner: Generators, coroutines and nanoservices PyCon US · 26 min
Open in YouTube
Step 1 of 5 · 1. List & dict comprehensions15 min read ·

1. List & dict comprehensions

big = [t for t in trades if t["qty"] >= 100]
by_id = {t["id"]: t for t in trades}          # dict comprehension
ids = {t["id"] for t in trades}                # set comprehension

Read it as: [output for item in iterable if condition]. Use them for simple transforms; switch to a normal loop when logic gets long.

Next: 2. Iterators and generators
‹ PrevNext ›