Python Foundations · Names & data
Comprehensions, iterators & generators
Build lists in one readable line, and stream big files without loading them into memory.
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 comprehensionRead 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