Creating collections concisely
Comprehensions combine iteration and optional filtering into an expression. They are ideal for straightforward transformations such as converting values, selecting records or building a lookup.
List, set and dictionary comprehensions
List comprehensions create lists, set comprehensions remove duplicates, and dictionary comprehensions create mappings. Generator expressions provide a lazy alternative when constructing the complete collection is unnecessary.
Readability comes first
A comprehension should remain understandable at a glance. If it contains multiple nested loops, complex conditions or side effects, a normal loop with descriptive intermediate variables is usually better.
Practice: convert a list of product dictionaries into a dictionary keyed by product ID while keeping only active products.