Comprehensions Intro
Comprehensions Intro
Section titled βComprehensions IntroβWhat it means
Section titled βWhat it meansβA comprehension is a compact syntax for building a new list, dict, or set by transforming and optionally filtering an existing iterable β in one expression instead of a multi-line for loop. They exist for lists ([...]), sets ({...}), and dicts ({k: v for ...}).
Examples
Section titled βExamplesβ# List comprehensionsquares = [n * n for n in range(6)] # [0, 1, 4, 9, 16, 25]
# With a filter conditionevens = [n for n in range(10) if n % 2 == 0] # [0, 2, 4, 6, 8]
# Dict comprehensionlengths = {word: len(word) for word in ["hi", "hello", "hey"]}# {'hi': 2, 'hello': 5, 'hey': 3}
# Set comprehensionunique_lengths = {len(word) for word in ["hi", "hey", "yo"]} # {2, 3}Common mistake
Section titled βCommon mistakeβWriting a comprehension so dense with nested loops or conditions that it becomes harder to read than the plain for loop it replaced β comprehensions are for simple transform/filter operations, not everything.
# Hard to read -- nested loop, unclear intentresult = [x*y for x in range(5) for y in range(5) if x != y if (x+y) % 2 == 0]
# Clearer as a regular loopresult = []for x in range(5): for y in range(5): if x != y and (x + y) % 2 == 0: result.append(x * y)Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
[x for x in items]and{x for x in items}?Answer
The first builds alist(ordered, duplicates allowed); the second builds aset(unordered, duplicates automatically removed). -
How do you filter items inside a comprehension?
Answer
Add anifcondition at the end:[x for x in items if condition]. -
When should you prefer a regular
forloop over a comprehension?Answer
When the logic involves multiple nested conditions/loops or side effects (like printing or writing to a file) β comprehensions should stay simple and side-effect-free.