- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Comprehensions and Generators
Python Comprehensions and Generators: Iterators and Lambda
lambda, and see how the iterator protocol drives every for loop. Then write generator functions and generator expressions that produce values lazily, and combine them with built-in functions and itertools into pipelines that handle large or endless data one item at a time.IntermediateLesson 2 of 9 in Intermediate Python Course
What you will learn
- Build new lists, dictionaries and sets from existing data in one readable expression, with filters, conditional values and nested loops, and judge when a plain loop reads better.
- Turn a loop into a list comprehensionRead and write the form
[expression for item in iterable], add a filter, and check that it builds the same list as the loop it replaces. - Choose between a filter and a conditional valueTell a trailing
if, which drops items, fromif ... elsebeforefor, which changes items, and combine several conditions correctly. - Write nested comprehensionsUse several
forclauses to flatten nested data or combine sequences, build lists of lists with a comprehension inside a comprehension, and keep nested forms readable. - Build dictionaries and sets with comprehensionsWrite
{key: value for ...}and{value for ...}to map, filter, invert and deduplicate data, and predict what happens to repeated keys and values. - Decide when a comprehension is the right toolWeigh readability, side effects and scope: know where comprehension variables live, when the walrus operator helps, and when a loop,
maporfilteris clearer.
- Turn a loop into a list comprehension
- Pass small functions to
sorted,min,maxand similar tools to control how items are compared, and write them inline withlambdawhere that keeps code clear.- Write lambda expressionsWrite anonymous one-expression functions with
lambda, compare them withdef, pass functions without calling them, and avoid the late-binding trap. - Sort with sorted, list.sort and key functionsSort any iterable by a computed key, in either direction and by several criteria, rely on stable sorting, and know when the original list changes.
- Pick extremes and top items with key functionsUse
min,max,heapq.nlargestand sorted slices with a key to find the best, worst and top few items, including ties and empty inputs.
- Write lambda expressions
- Describe the iterator protocol behind every
forloop, predict when an iterator is used up, and write classes that work inforloops.- Tell iterables and iterators apartDefine iterables and iterators, step through an iterator with
iter()andnext(), and recognize which common objects are which. - Trace how a for loop consumes an iteratorRewrite a
forloop withiter()andnext(), predict what happens when an iterator is reused, and avoid changing a collection while looping over it. - Implement the iterator protocol in a classWrite an iterator class with
__iter__and__next__, and an iterable class that hands out a fresh iterator for every loop.
- Tell iterables and iterators apart
- Produce values lazily, one at a time, with generator functions and generator expressions, and control how generators delegate, finish and clean up.
- Write generator functions with yieldWrite functions that
yieldvalues, trace how a generator pauses and resumes, and know what calling a generator function actually returns. - Produce data lazily and work with infinite sequencesUse laziness to save memory and time, take values safely from infinite generators, and predict when a generator's code runs and raises errors.
- Write generator expressionsWrite lazy one-line generators with parentheses, pass them straight to functions such as
sumandany, and choose between a generator expression and a list comprehension. - Delegate to sub-generators and control running generatorsUse
yield fromto delegate, return a final value, end a generator correctly, and useclose()andsend()on a running generator.
- Write generator functions with yield
- Connect generators, built-in iterator functions and the
itertoolsmodule into pipelines that process data step by step without building intermediate lists.- Chain generator stages into a pipelineBuild a pipeline from small generator stages and built-in iterator functions, trace how one item flows through it, and debug it without losing data.
- Slice, combine and filter streams with itertoolsUse
islice,count,cycle,repeat,chain,takewhile,dropwhile,filterfalse,compress,zip_longest,pairwise,batchedandteeto reshape iterators lazily. - Group, accumulate and map with itertoolsSummarize streams with
groupbyandaccumulate, apply functions to tuples withstarmap, and avoid the classicgroupbymistakes. - Generate products, permutations and combinationsReplace nested loops with
itertools.product, list arrangements and selections withpermutationsandcombinations, and predict how many results each produces.
- Chain generator stages into a pipeline
Python Comprehensions and Generators study guide
1Build collections with comprehensions
A comprehension turns a collection-building loop into an expression. Start by locating the input, the value to keep, and any rule for skipping items; then choose a list, dictionary, or set to hold the result. More involved forms can flatten rows or build a grid, but compact syntax helps only while the operation remains easy to read. Scope, repeated keys, and shared rows explain several results that can otherwise look surprising.
1.1 From append to an expression
A list comprehension builds a new list from an iterable, an object Python can loop over. Its form is [expression for item in iterable]. The expression describes one result, while the for clause supplies each input in turn.
Move the appended value to the front
Consider a loop that converts distances from kilometers to meters:
lengths_km = [3, 12, 5]
lengths_m = []
for distance in lengths_km:
lengths_m.append(distance * 1000)
The source is lengths_km, the temporary name is distance, and the appended value is distance * 1000. Place that value before the for clause:
lengths_m = [distance * 1000 for distance in lengths_km]
Both versions give [3000, 12000, 5000]. The source remains [3, 12, 5]: this expression creates a new list. Assign it to a name if you need to keep the result. Simply evaluating a comprehension does not replace the source list.
The same conversion works for a loop building squares: [n * n for n in range(1, 6)] gives [1, 4, 9, 16, 25]. Read the for clause first to find the inputs, then read the front to find what each becomes.
Keep only selected inputs
A trailing if guards the expression:
words = ["apple", "fig", "banana", "kiwi"]
long_words = [word.upper() for word in words if len(word) > 3]
For each word, Python first tests its length. It skips "fig" and calls .upper() on the remaining words, giving ['APPLE', 'BANANA', 'KIWI']. A rejected input never reaches the transformation. This matches a loop whose append sits inside an if block.
Without a filter, there is one result per input; with a filter, there are at most that many. An empty source produces []. These counts are useful when checking whether a condition accidentally removed valid data.
Change the source or result expression
The iterable can be a tuple, string, range, set, dictionary, or open file. [c for c in "Python 3.12" if c.isdigit()] gives ['3', '1', '2']. The output follows the source's iteration order; using a set as input does not give a defined order.
A dictionary supplies keys by default. Use .items() to unpack names and quantities:
stock = {"pens": 12, "pads": 3}
labels = [f"{name}={qty}" for name, qty in stock.items()]
Here labels is ['pens=12', 'pads=3']. An expression may also call a function or build a tuple. Write tuples with parentheses: [(n, n ** 2) for n in range(3)] gives [(0, 0), (1, 1), (2, 4)]. The form [n, n ** 2 for n in range(3)] is invalid syntax because the two values are not grouped as one result.
Key Takeaways
- A list comprehension puts the result expression before the
forclause. - A trailing filter runs before the result expression for that item.
- Use
.items()to unpack dictionary key–value pairs. - Assign the new list; building it does not replace the source.
1.2 Keep an item or change its value
An if in a comprehension can do two different jobs. A filter decides whether an input produces a result. A conditional expression decides what value to produce. The distinction matters whenever positions must continue to match the input.
Compare removal and replacement
readings = [12, -3, 7, -1, 0]
kept = [r for r in readings if r >= 0]
clipped = [r if r >= 0 else 0 for r in readings]
kept is [12, 7, 0]: two negative readings disappear. clipped is [12, 0, 7, 0, 0]: each negative becomes zero and all five positions remain. If each position represents a measurement time, filtering would shift later readings away from their original positions.
| Job | Position | Effect |
|---|---|---|
| Filter | After the for clause | Keeps or drops the input |
| Conditional value | Before for, with else | Chooses the output value |
The placement follows the grammar. [r for r in readings if r >= 0 else 0] is a SyntaxError: a trailing filter cannot have else. A conditional expression needs both branches, so [r if r >= 0 for r in readings] is also invalid.
Trace a combined expression
names = ["ada", "", None, "grace"]
labels = [
name.title() if name else "(missing)"
for name in names
if name is not None
]
The trailing filter first removes None. Of the remaining inputs, "ada" becomes 'Ada', the empty string becomes '(missing)', and "grace" becomes 'Grace'. Thus labels is ['Ada', '(missing)', 'Grace']. The conditional expression does not run for the removed input.
Only the chosen conditional branch is evaluated. [100 // d if d else None for d in [5, 0, 4]] gives [20, None, 25]: Python never divides by zero. If missing positions are unnecessary, [100 // d for d in [5, 0, 4] if d != 0] gives [20, 25]. Here the filter prevents the division altogether.
State the actual condition
Several trailing filters work like and. [n for n in range(1, 31) if n % 2 == 0 if n % 3 == 0] gives [6, 12, 18, 24, 30], just as one filter joining both tests with and does. Use or when either condition should be enough.
A bare if x tests truthiness. It removes zeros, empty strings, None, and empty containers. For [0, 1, "", "a", None, [], [2]], filtering on if x gives [1, 'a', [2]]. If zero is a valid measurement and only None means missing, use if x is not None; otherwise the filter silently discards valid zeros.
Key Takeaways
- A trailing
ifremoves inputs;a if condition else bchooses values. - A conditional value keeps one output per input unless a separate filter removes it.
- Only the selected conditional branch runs.
- Several filters combine like
and. - Truthiness removes zero and empty values as well as
None.
1.3 Flatten rows and build independent grids
Multiple for clauses follow the order of ordinary nested loops. The leftmost clause is the outer loop. Parentheses inside the expression group a tuple; another pair of square brackets creates a nested list.
Follow the loops from left to right
grid = [[1, 2, 3], [4, 5], [6]]
flat = [x for row in grid for x in row]
First row is [1, 2, 3], so the inner loop contributes 1, 2, 3. The next row contributes 4, 5, and the last contributes 6. The result is [1, 2, 3, 4, 5, 6]. Empty rows contribute nothing.
Do not reverse the clauses. In [x for x in row for row in grid], Python needs row before the comprehension binds it. With no existing row, this raises NameError; with an old row, it can silently read the wrong data.
Independent sources create every pair. [(size, color) for size in ["S", "M"] for color in ["red", "blue", "green"]] produces six pairs, exhausting the three colors for "S" before moving to "M". An inner source can also depend on the outer value: [(a, b) for a in range(1, 4) for b in range(a, 4)] gives [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)].
Preserve a row structure
table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
Each outer iteration builds a whole inner list. The result is [[1, 2, 3], [2, 4, 6], [3, 6, 9]]. Two for clauses inside one pair of square brackets flatten results; a comprehension inside the expression creates rows.
For transposition, select one column at a time:
matrix = [[1, 2, 3], [4, 5, 6]]
columns = [[row[i] for row in matrix] for i in range(3)]
columns is [[1, 4], [2, 5], [3, 6]]. For this rectangular matrix, [list(col) for col in zip(*matrix)] gives the same result.
Create new mutable rows
[[0] * 3 for _ in range(3)] constructs a separate list on each iteration. The underscore means the iteration value is unused. In contrast, [[0] * 3] * 3 repeats references to one row. After setting its first cell to 1, all rows display [1, 0, 0]. A comprehension avoids this shared-row bug by rerunning the row-building expression.
Recognize the Python 3.15 form
Python 3.15 supports [*row for row in grid] for one-level flattening, {*s for s in sets} for set union, and {**d for d in dicts} for dictionary merging. Later dictionaries win on repeated keys. Python 3.14 and earlier reject these comprehension forms; use ordinary nested clauses or itertools.chain.from_iterable there.
Split long comprehensions across lines within their delimiters. When several nesting levels or conditions obscure the loop order, a helper function or explicit loop makes the data flow easier to inspect.
Key Takeaways
- Read multiple
forclauses in nested-loop order, left to right. - Nested square brackets build lists of lists.
- Build each mutable row separately to avoid shared references.
- Transpose a rectangular matrix by collecting each column.
- Unpacking at the front of comprehensions requires Python 3.15.
1.4 Choose list, dictionary, or set results
Braces choose a dictionary or set comprehension. A colon between the two result expressions makes a dictionary: {key_expr: value_expr for item in iterable}. Without that colon, {expr for item in iterable} builds a set.
Map keys to values
{w: len(w) for w in ["red", "green", "blue"]} gives {'red': 3, 'green': 5, 'blue': 4}. Each word becomes a key and its length becomes the value. With parallel data, unpack pairs from zip:
names = ["Ada", "Lin", "Sam"]
scores = [91, 78, 85]
results = {name: score for name, score in zip(names, scores)}
results is {'Ada': 91, 'Lin': 78, 'Sam': 85}. If no transformation or filter is needed, dict(zip(names, scores)) expresses the same operation directly. zip stops at its shortest input, so unequal inputs need attention when every name must have a score.
To transform an existing dictionary, iterate over .items(). {name: score for name, score in results.items() if score >= 80} gives {'Ada': 91, 'Sam': 85}. Replacing the value expression with score + 5 adjusts values in the new dictionary without updating results.
Follow repeated keys
A dictionary keeps one value per key. When a later item produces an existing key, its value overwrites the old value; the key keeps its original insertion position.
colors = {"apple": "red", "cherry": "red", "lime": "green"}
inverted = {color: fruit for fruit, color in colors.items()}
The first pair adds 'red': 'apple'. The second replaces the value with 'cherry', and the third adds 'green': 'lime'. The result is {'red': 'cherry', 'green': 'lime'}. To preserve every fruit, group them into lists with a loop and setdefault.
Keys must be hashable. Strings and numbers work, as do tuples whose members are hashable. Lists cannot be keys; attempting to use one raises TypeError. Convert a list-shaped key to a tuple when its contents are suitable.
Deduplicate with a set
{w.lower() for w in ["Tea", "tea", "TEA", "Coffee"]} contains just 'tea' and 'coffee'. Set elements must also be hashable. Sets have no defined iteration order. Use sorted(...) for a predictable display: ['coffee', 'tea'].
| Result | Keeps duplicates? | Access pattern |
|---|---|---|
| List | Yes | Position and iteration order |
| Dictionary | One value per key | Lookup by key |
| Set | No | Membership and unique values |
Empty braces {} make a dictionary. Use set() for an empty set; an empty set comprehension also produces set(). Parentheses around a comprehension create a generator expression, not a tuple. tuple(x * 2 for x in range(3)) explicitly builds (0, 2, 4).
For counting, {w: words.count(w) for w in set(words)} rescans the words for every distinct key. With "the cat and the hat".split(), 'the' has count 2. collections.Counter(words) performs the count in one pass and avoids those repeated scans on large inputs.
Key Takeaways
- A colon in a brace comprehension separates dictionary keys and values.
- Later duplicate keys replace values but keep the key position.
- Dictionary keys and set elements must be hashable.
- Sets remove duplicate values and have no defined iteration order.
- Use
set()for an empty set andtuple(...)to build a tuple. - Use
Counterfor efficient frequency counts.
1.5 Keep transformations readable
Choose a comprehension when the main result is a new collection. Choose a loop when the work consists of actions, early stopping, or several steps of error handling. Short syntax is useful only if it makes the operation clear.
Match the form to the work
[print(x) for x in items] performs the printing, but it also builds a list of None values that is usually thrown away. An explicit for loop shows that the action is the purpose. A comprehension visits every input and has no break; find a first match with a loop or next((n for n in nums if n > 100), None). With [5, 120, 40, 300], that expression returns 120 without examining later values.
A conversion can fail partway through. values = [int(s) for s in ["4", "x", "6"]] raises ValueError at "x". Assignment has not finished, so values retains its old binding or remains undefined. No partial result is assigned. To recover for individual inputs, put try and except inside a loop or use a parsing helper with an explicit missing-result policy.
Know where names are bound
A comprehension's loop variable stays local to the comprehension:
x = "old"
doubled = [x * 2 for x in range(3)]
doubled is [0, 2, 4] and outer x is still 'old'. A normal for loop leaves its loop name bound after the loop. Comprehensions can read surrounding names: with factor = 3, [n * factor for n in range(4)] gives [0, 3, 6, 9].
The assignment expression, :=, follows a different scope rule. It binds a name in the surrounding scope and can avoid repeating a calculation:
data = [1, 2, 3, 4, 5]
large_squares = [y for x in data if (y := x * x) > 10]
Each square is computed in the filter, stored in y, and tested. Accepted values reach the front expression, giving [16, 25]; afterward y is 25. Another useful form is [clean for raw in lines if (clean := raw.strip())], which strips once and drops blank results. The walrus operator requires Python 3.8 or newer and is forbidden in a comprehension's iterable expression after in.
Compare equivalent tools
map applies a function and filter keeps inputs passing a test. Both return lazy iterators in Python 3. list(map(str.upper, words)) gives the same values as [word.upper() for word in words]. An existing named function often reads naturally with map; a simple expression often reads better as a comprehension than as a new lambda.
Use meaningful variable names and split long expressions inside their delimiters. PEP 8 suggests lines of at most 79 characters. A straightforward comprehension is often a little faster than its append loop, but complex nesting, hidden side effects, or nested conditional expressions cost more in readability than they save in space.
Key Takeaways
- Use loops for actions, early stopping, and per-item exception handling.
- Comprehension loop names do not overwrite surrounding names.
- A walrus target binds in the surrounding scope and can reuse a computed value.
mapandfilterreturn lazy iterators in Python 3.
2Sort and select with key functions
A key function describes which feature of an item should control its position or selection. Sorting and selecting then return the original items, so records keep their full information. Small lambdas can express a custom key, while existing functions often express it more clearly. Stable ordering, tuple keys, and explicit empty-input handling let you control ties, combine criteria, and choose the right tool for one extreme or a few top results.
2.1 Small functions as arguments
A lambda expression creates a function from one expression: lambda parameters: expression. The function returns the expression's value when called. (lambda x: x * 2)(6) returns 12; creating the lambda itself does not perform the multiplication.
Pass the operation
A common use is to pass a small function to an operation that will call it later:
words = ["kiwi", "banana", "fig"]
ordered = sorted(words, key=lambda word: word[-1])
The keys are 'i', 'a', and 'g', so ordered is ['banana', 'fig', 'kiwi']. The result contains words, not their last letters. If an existing function already expresses the operation, pass it directly: key=len sorts by length and key=str.lower ignores case for ordinary English text.
key=len() instead calls len immediately without an argument, raising TypeError before sorting starts. The sorter needs the function object so it can call that function on each item.
Understand the expression limit
A lambda can have no parameters, several parameters, defaults, or *args. (lambda a, b: a + b)(3, 4) gives 7. (lambda x, n=2: x ** n)(5) gives 25, and supplying n=3 with x=2 gives 8.
Its body must be one expression. A conditional expression is allowed: (lambda n: "negative" if n < 0 else "not negative")(-4) returns 'negative'. Statements such as ordinary assignment, return, loops, and try cannot form the body, and lambda parameters cannot have type annotations.
Use def for a named, reusable function. It supports several steps, a docstring, and a useful function name in tracebacks. PEP 8 recommends it over assigning a lambda to a name. A lambda's own __name__ is '<lambda>'.
Capture a loop value deliberately
funcs = [lambda: i for i in range(3)]
results = [func() for func in funcs]
results is [2, 2, 2]. The functions look up the shared i when called, after the comprehension has finished. This is late binding. The fact that i does not leak into the surrounding scope does not give each lambda a separate saved value.
A default parameter saves the current value when that function is created:
funcs = [lambda i=i: i for i in range(3)]
results = [func() for func in funcs]
Now the result is [0, 1, 2]. A function defined with def inside a loop has the same late-binding behavior for names it reads from the enclosing scope.
For transformations, list(map(lambda m: m / 1000, [250, 1500])) gives [0.25, 1.5]. For selection, list(filter(lambda n: n % 3 == 0, range(10))) gives [0, 3, 6, 9]. The corresponding comprehensions often make these simple operations easier to read.
Key Takeaways
- A lambda creates a function with a single expression body.
- Pass a function as
key, without calling it. - Use
defwhen the function needs a name or multiple steps. - Late binding reads an enclosing name at call time; a default can save its current value.
2.2 Order records and preserve ties
sorted(iterable) builds a new sorted list from any iterable. a_list.sort() changes that list in place and returns None. Assigning nums = nums.sort() therefore loses the list binding; write nums.sort() or assign sorted(nums).
Compute a key, keep the record
Without a key, Python compares items with <. Strings follow character ordering, so sorted(["banana", "Cherry", "apple"]) gives ['Cherry', 'apple', 'banana']. A key changes the comparison: key=str.lower gives ['apple', 'banana', 'Cherry']. For broader case-insensitive text matching, str.casefold handles distinctions that .lower() retains: "Straße".casefold() gives 'strasse'.
people = [("Ana", 34), ("Ben", 27), ("Cleo", 34), ("Dev", 22)]
by_age = sorted(people, key=lambda person: person[1])
Python calls the key once per element, producing 34, 27, 34, and 22. It orders by those values but returns [('Dev', 22), ('Ben', 27), ('Ana', 34), ('Cleo', 34)]. Ana remains before Cleo because sorting is stable: equal keys preserve original relative order.
reverse=True makes the key order descending while preserving stability. The result is [('Ana', 34), ('Cleo', 34), ('Ben', 27), ('Dev', 22)]. Reversing an already sorted ascending list would also reverse each tied group, putting Cleo before Ana.
Combine criteria
A tuple key compares its components in order. key=lambda person: (-person[1], person[0]) orders age descending and then name ascending. Negation reverses a numeric criterion; it cannot reverse a string criterion.
Use stable passes when criteria need other direction combinations. Sort by the secondary criterion first, then by the primary criterion. Sorting names descending and then ages ascending gives [('Dev', 22), ('Ben', 27), ('Cleo', 34), ('Ana', 34)]. The final age pass preserves the name order within each equal-age group.
The operator module supplies ready-made keys: itemgetter(1) reads index 1, itemgetter(1, 0) returns a two-part tuple, and attrgetter("age") reads an object's age attribute.
Sort dictionary data and mixed values
For stock = {"pens": 12, "tape": 3, "ink": 7}, choose the desired output:
| Expression | Result |
|---|---|
sorted(stock) | ['ink', 'pens', 'tape'] |
sorted(stock, key=stock.get) | ['tape', 'ink', 'pens'] |
sorted(stock.items(), key=lambda kv: kv[1]) | [('tape', 3), ('ink', 7), ('pens', 12)] |
Wrapping sorted pairs in dict(...) creates a dictionary in that insertion order.
Incompatible keys cause TypeError. sorted([3, "2", 1], key=int) gives [1, '2', 3]: converting the keys makes comparison possible but leaves the items unchanged. For numbers mixed with None, key=lambda v: (v is None, v) places numbers first and None last. Its first component separates the groups, so numbers never need to compare directly with None.
Key Takeaways
sortedreturns a new list;.sort()changes a list and returnsNone.- A key is called once per element, while results retain the original items.
- Stable sorting preserves equal-key order, including with
reverse=True. - Tuple keys compare criteria left to right.
- Stable multi-pass sorting handles the secondary criterion first.
- Choose comparable key values for mixed inputs.
2.3 Find an extreme or a short ranked list
min and max select one original item according to a key. They do not return the key itself. For the word list ["ox", "zebra", "cat", "horse"], max(words, key=len) returns 'zebra', while max(len(word) for word in words) returns 5.
Decide how ties should work
The first item with the best key wins. With people = [("Ana", 34), ("Ben", 27), ("Cleo", 34), ("Dev", 22)], max(people, key=lambda person: person[1]) returns ('Ana', 34) and min with the same key returns ('Dev', 22). Ana wins the largest-age tie because she appears first.
Use a tuple key if another field should decide a tie. Be explicit about its direction: max selects the largest entire key tuple, including its later components. An added name criterion can therefore change a tie winner even when the ages match.
Handle an empty iterable
max([]) raises ValueError. A default makes the empty case explicit:
oldest = max(people, key=lambda person: person[1], default=None)
This returns None only when the input is empty. It does not insert None into the competition or call the key on it. The keyword works with the single-iterable form. max(1, 2, default=0) is a TypeError because separate positional values use another form of the function.
Several separate arguments are otherwise valid. max(3, 9, 4) is 9, and min(-7, 3, -2, key=abs) is -2: the item nearest zero, not its absolute value.
Select dictionary keys or values
With stock = {"pens": 12, "tape": 3, "ink": 7}, max(stock) returns 'tape', the greatest key by string order. max(stock.values()) returns 12. max(stock, key=stock.get) returns 'pens', the key whose associated quantity is greatest. Choose the iterable and key together to match the question you need to answer.
Return the top few items
import heapq
scores = [72, 95, 88, 61, 95, 79]
top_three = heapq.nlargest(3, scores)
bottom_two = heapq.nsmallest(2, scores)
The results are [95, 95, 88] and [61, 72]. Duplicates are retained: ranking does not deduplicate values. Both functions accept key, so they can rank full records as well.
nlargest(n, data, key=k) matches sorted(data, key=k, reverse=True)[:n]; nsmallest matches sorted(data, key=k)[:n]. The heap tools do less work when the requested count is small compared with the input. Sorting is simple when most of the ordered data is needed, and min or max is the natural choice for one item. All these selections must inspect the complete finite input to establish the extreme.
Key Takeaways
minandmaxreturn original items and keep the first best-key tie.- Use
defaultfor empty inputs in the single-iterable form. - Choose dictionary keys, values, or value-ranked keys deliberately.
nlargestandnsmallestreturn ranked lists and retain duplicates.
3Follow the iterator protocol
Every for loop asks an iterator for successive values. A list stores data that many iterators can traverse, while each iterator stores the progress of one pass. Following that progress explains why a second loop can be empty, why a membership test changes what comes next, and why mutation can skip items. The same small protocol lets your own classes supply either a single stream or a fresh iterator for every pass.
3.1 Separate the data source from one pass
An iterable is an object that iter() can turn into an iterator. An iterator supplies successive values through next(). A list is iterable, but it is not itself an iterator: it stores the values, while a list iterator tracks a position.
Step through one iterator
letters = ["a", "b"]
it = iter(letters)
first = next(it)
second = next(it)
end = next(it, "done")
first is 'a', second is 'b', and end is 'done'. Without that default, the third next(it) raises StopIteration, the signal that no values remain. Once exhausted, an iterator stays exhausted; later calls also stop or return the supplied default.
An iterator defines __next__ and __iter__; its __iter__ returns itself. This makes every iterator an iterable too. A loop can accept an iterator wherever it accepts an iterable, but getting its iterator does not restart it.
Give each pass its own position
numbers = [4, 8]
left = iter(numbers)
right = iter(numbers)
The first next(left) gives 4, the second gives 8, and the first next(right) still gives 4. Each iterator has its own progress through the same list. Think of the list as a book and each iterator as a bookmark. Taking a new bookmark does not change the book or the position of another bookmark.
next(numbers) raises TypeError: a container needs an iterator to provide a current position. Lists, tuples, strings, sets, and dictionaries are common iterables. Dictionary views from .keys(), .values(), and .items() are reusable iterables too.
Laziness and single use are different properties
range computes values on demand but remains a reusable sequence. It supports length, indexing, and efficient integer membership tests. next(range(3)) raises TypeError; use next(iter(range(3))) to get 0.
By contrast, map, filter, zip, enumerate, reversed, generator objects, and open file objects are iterators. Advancing them changes the state of that pass. Calling iter(obj) on an iterator returns the same object: iter(obj) is obj is True.
| Object | Reusable data or sequence? | Direct next()? |
|---|---|---|
| List | Yes | No |
range | Yes | No |
| List iterator | One pass | Yes |
| Generator object | One pass | Yes |
Check whether iteration is supported
isinstance(obj, collections.abc.Iterator) checks the iterator interface. collections.abc.Iterable does not recognize every object accepted by iter: the older sequence protocol can supply __getitem__ starting at index 0 and raise IndexError at the end. Calling iter(obj) and catching TypeError tests whether Python can actually iterate over the object.
Key Takeaways
- An iterable provides an iterator; an iterator provides successive values.
- An iterator returns itself from
iter()and signals exhaustion withStopIteration. - Each list iterator has its own position.
rangeis lazy and reusable, while generators are single-pass.- Calling
iteris the reliable way to test whether iteration is supported.
3.2 Track every operation that consumes values
A for loop calls iter once, then repeatedly requests the next value. It catches StopIteration from that request and ends normally. The loop body runs only after a value has been obtained.
Expand the loop
it = iter(obj)
while True:
try:
value = next(it)
except StopIteration:
break
print(value)
The try surrounds the request, not the body. This preserves the distinction between ordinary exhaustion and an unrelated exception from processing a value. A for loop follows the same pattern without making you write the machinery.
Many other operations consume values: list, tuple, set, sum, min, max, sorted, str.join, comprehensions, and unpacking. any, all, and a successful membership test can stop early.
Follow the shared position
After pairs = zip([1, 2, 3], "abc"), list(pairs) gives [(1, 'a'), (2, 'b'), (3, 'c')]. A second list(pairs) gives []. The first call consumed the stream. To make several passes, store the first result in a list or create a new zip.
A membership search also advances an iterator:
it = iter([1, 2, 3, 4])
found = 3 in it
remaining = list(it)
found is True and remaining is [4]: the search consumed the matching 3 too. A failed search consumes all remaining values. The same position sharing is useful for skipping a header: call header = next(lines) and then loop over lines to process the remaining rows. Use a default if an empty input should be handled without an exception.
Unpacking consumes as well. first, *rest = iter(range(5)) gives first as 0 and rest as [1, 2, 3, 4]. Starred unpacking must collect the remainder. a, b = iter([1, 2, 3]) raises ValueError because there are too many values.
Avoid changing collection structure mid-pass
A list iterator moves through positions, so deletion can shift an unvisited item behind its position. With [1, 2, 2, 3], removing each encountered 2 leaves [1, 2, 3]: the second 2 shifts left and gets skipped.
Build [n for n in nums if n != 2] to obtain [1, 3], or loop over a snapshot such as nums[:] when you must update the original list. A snapshot stabilizes the iteration source.
Adding or removing dictionary keys or set elements during iteration can raise RuntimeError because their size changes. For dictionary deletion, loop over list(d) or build a new dictionary. Updating an existing key's value does not change the key set and is allowed.
Key Takeaways
- A loop gets its iterator once and requests a value before each body execution.
- Membership, unpacking, and inspection can consume an iterator.
- A second consumer continues from the current position.
- Materialize data or recreate its iterator for another pass.
- Use a new collection or a snapshot when deleting during iteration.
3.3 Make a class work in loops
An iterator class keeps progress in its attributes. Its __next__ returns a value and updates that progress, or raises StopIteration when finished. Its __iter__ returns self, allowing loops to use the same iterator.
Implement a single pass
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
For Countdown(3), the first call saves 3, changes current to 2, and returns 3. The next calls return 2 and 1. When current reaches 0, every later call raises StopIteration. Saving before decrementing avoids losing the starting value.
After c = Countdown(2), list(c) gives [2, 1] and a second call gives []. This class has no reset method or __len__; create another instance for a fresh pass. The protocol requires only __iter__ and __next__, though a class may provide additional methods.
Provide fresh iterators for reusable data
A container-like class should hand out a new iterator for each pass:
class Playlist:
def __init__(self, songs):
self.songs = list(songs)
def __iter__(self):
return iter(self.songs)
With Playlist(["intro", "theme"]), every list call gives ['intro', 'theme']. Nested loops get separate iterators too. Returning self from a stateful container would make those loops compete for one position.
A generator method can also provide fresh progress:
class ReusableCountdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
Each iter call creates a fresh generator with its own local n. For ReusableCountdown(3), repeated list conversions give [3, 2, 1]. The stored starting value remains unchanged.
Signal the end correctly
None is a valid iterated value, not an end signal. If an iterator repeatedly returns None after its data ends, a loop continues receiving None forever. Raise StopIteration instead. A class with __next__ but no __iter__ can fail in for because the loop first needs iter(obj).
An iterator may intentionally never raise StopIteration, giving an infinite stream. Its consumer then needs a limit or break. The older indexed protocol also permits iteration through __getitem__(0), __getitem__(1), and so on until IndexError; new iterable classes normally express the contract with __iter__.
Key Takeaways
- Iterator classes return
selffrom__iter__and advance in__next__. - Raise
StopIterationat the end;Noneis an ordinary value. - Reusable iterable classes provide fresh iterator state for each pass.
- A generator
__iter__method creates fresh local state on each call.
4Produce values with generators
A generator keeps a function's place while handing values to its caller one at a time. Following each pause and resumption shows when calculations happen, when exceptions appear, and how a file can remain open between requests. Generator expressions provide the same single-pass behavior for compact transformations. Delegation and explicit cleanup extend the model when several helpers or resources take part in producing the stream.
4.1 Pause and resume a function with yield
A function containing yield in its body is a generator function, even if that statement lies in a branch that never runs. Calling it returns a generator object, an iterator. The function body starts only when the consumer requests a value.
Trace each request
def steps():
print("start")
yield 1
print("middle")
yield 2
print("end")
g = steps() prints nothing. The first next(g) prints start, returns 1, and pauses at the first yield. The second prints middle, returns 2, and pauses again. The third prints end, reaches the end of the body, and raises StopIteration.
Local variables and the execution position survive the pause. The next request continues immediately after the previous yield; it does not start the function again. Calling steps() again creates a separate generator with fresh state.
Replace building a list with yielding values
def evens(limit):
for n in range(0, limit, 2):
yield n
list(evens(10)) is [0, 2, 4, 6, 8]. The generator supplies 0, pauses, then supplies 2 on the next request. A list-building function would compute and store every result before returning its list. Here the consumer chooses whether to take one value, several values, or all of them.
A yield can be inside a loop or condition. It hands out one value while preserving the ability to continue. An ordinary return exits the function; in a generator, it ends production instead of yielding an additional item.
Understand the final return
def one_item():
yield 1
return "done"
list(one_item()) gives [1]. The string is stored in the final StopIteration exception's .value, which a for loop or list ignores. It is not another output item. To inspect it manually, catch the exception raised after the yielded 1 and read exc.value. Delegating generators can receive this return value through yield from.
| Statement | Effect in a generator |
|---|---|
yield value | Supplies one item and pauses |
return value | Ends the stream with a final return value |
| End of body | Ends the stream normally |
Treat the object as a stream
Printing evens(10) shows a generator-object representation, not the numbers. Iterate over it or use list to inspect a finite result. The object has no length or indexing interface: len(evens(4)) and evens(4)[0] raise TypeError.
Once consumed, a generator stays exhausted. If g = evens(4), the first list(g) gives [0, 2], and the second gives []. Keep a list if you need repeated access, or call evens(4) again to produce a new stream.
Key Takeaways
- Calling a generator function creates an iterator without running its body.
nextresumes after the previousyieldand runs to the next one.- Local variables and execution position survive each pause.
returnends the stream; its value is not a yielded item.- Create a new generator for a fresh pass.
4.2 Control lazy work and resource lifetime
Lazy evaluation computes values when requested. A generator keeps its position and local state instead of saving every value already yielded. Memory use depends on what that state retains: a generator with an ever-growing history list still grows.
Separate storage from production
A million-element list holds a million references as well as retaining the objects they refer to. On a measured 64-bit CPython 3.12 system, sys.getsizeof([n for n in range(1_000_000)]) was about 8.4 MB for the list alone, while the corresponding generator object was 192 bytes. These are object-size measurements, not total process memory; exact sizes vary by version. A generator that appends to a history list gives up that storage advantage.
Stateful production can still keep only a few running values:
def running_mean(values):
total = 0
for count, value in enumerate(values, start=1):
total += value
yield total / count
For [4, 8, 6], the total becomes 4, 12, and 18; dividing by counts 1, 2, and 3 yields [4.0, 6.0, 6.0].
Limit an endless source
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
list(islice(fibonacci(), 10)) gives [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. The tuple assignment updates both state values from the old pair. list(fibonacci()) never completes and keeps accumulating output. Use islice, a stopping predicate, a loop with break, or a fixed number of requests. zip(range(3), fibonacci()) also limits output because its finite first input ends.
Expect errors when execution reaches them
g = (10 // n for n in [2, 0]) is created successfully. The first request returns 5; the second raises ZeroDivisionError. An argument check at the top of a generator function is delayed too. If validation must happen at call time, use an ordinary function to validate and then return a generator.
Keep a file open while yielding
def non_blank(path):
with open(path, encoding="utf-8") as source:
for line in source:
if line.strip():
yield line.rstrip("\n")
The file opens on the first request and remains open while the generator is paused inside with. It closes when execution leaves the block, including when a started generator is explicitly closed. If you stop early and keep the generator, close it to release the file promptly; break alone does not close it.
An ordinary function that returns (line.strip() for line in source) from inside with closes the file before the returned generator is consumed. Iteration then raises ValueError for reading a closed file. Yield inside the block, or return an eagerly built list if all data should be read before return.
Key Takeaways
- Lazy values are computed on request, so execution errors may appear later.
- Memory depends on retained state, including any buffered history.
- Use a bounded consumer for an infinite source.
- A generator can preserve running totals between yields.
- Keep resource use inside the yielding lifetime and close a started generator after early stopping.
4.3 Use a generator expression once
A generator expression uses comprehension-style clauses inside parentheses: (expression for item in iterable if condition). It returns an iterator and calculates accepted values on request. Parentheses do not create a tuple comprehension.
Feed a consumer directly
total = sum(n * n for n in range(1, 11))
label = ", ".join(str(n) for n in [1, 2, 3])
total is 385 and label is '1, 2, 3'. Because each generator expression is the only argument, its own parentheses can be omitted. With another argument, retain them: sum((n * n for n in range(4)), start=100) is 114. Omitting the inner parentheses in that form is a SyntaxError.
Stop when the answer is known
any ends at the first truthy result, and all ends at the first falsy result. With readings = [7, 250, 3, 9], any(n > 100 for n in readings) tests only 7 and 250. In any([n > 100 for n in readings]), the whole list is built before any gets control, so all four comparisons run.
For a first matching item, use next with a default: next((w for w in ["apple", "zinc", "zoo"] if w.startswith("z")), None) gives 'zinc'. Searching for "q" gives None; without a default it would raise StopIteration.
Trace what is captured and what is delayed
The leftmost iterable expression is evaluated and its iterator obtained when the generator expression is created. The body, filters, and later iterable expressions run during consumption. (x for x in 5) therefore raises TypeError immediately.
data = [1, 2]
g = (x * 10 for x in data)
data = [7]
list(g) gives [10, 20]. Rebinding data does not replace the iterator already created over the original list. If you append 3 to that original list before consumption instead, its list iterator sees the appended value and the output is [10, 20, 30].
Other names are read later. After factor = 2, g = (x * factor for x in [1, 2]), and factor = 3, consuming g gives [3, 6]. Saving the source iterator is not the same as saving every variable's value.
Choose whether to materialize
Generator expressions can form stages: strip strings, drop blank results, then convert accepted strings to integers. With raw = ["10", " 4", "", "6 "], those stages sum to 20. Naming the stages creates no output list; the final consumer pulls values through them.
A generator is single-use. After consuming (c.upper() for c in "abc"), the next list conversion is []. Use a list when you need several passes, length, indexes, or slices. Also examine the consumer: sorted(g) still builds a full list, even though its input is lazy.
Key Takeaways
- A generator expression produces a single-pass iterator.
- Omit its own parentheses only when it is the sole function argument.
any,all, andnextcan stop production early.- The leftmost iterator is obtained at creation; other work and name lookups are delayed.
- Choose a list for repeated access, indexing, or length.
4.4 Delegate, finish, and close generators
yield from iterable delegates production to another iterable. It passes through each yielded item, allowing a larger generator to be built from smaller helpers. With a generator helper, it also receives that helper's final return value.
Separate output items from a final value
def numbered(items):
count = 0
for item in items:
count += 1
yield f"{count}. {item}"
return count
def report(items):
total = yield from numbered(items)
yield f"{total} items"
For ["tea", "milk"], report yields ['1. tea', '2. milk', '2 items']. The helper's return count supplies 2 to the yield from expression. The outer generator uses it to build the final string; the helper does not itself yield that count.
For simple concatenation, loop over sources and yield from each one. Delegating to [1, 2], "ab", and range(3) gives [1, 2, 'a', 'b', 0, 1, 2].
Finish without leaking StopIteration
End generator code with return or by reaching the end of its body. Since Python 3.7, a StopIteration escaping from the body is converted to RuntimeError: generator raised StopIteration under PEP 479. A bare next on an exhausted helper can cause this unexpectedly. Catch the exhaustion and return, or use an appropriate default. The iterator protocol still uses StopIteration; the rule concerns an exception escaping generator body code.
Release resources explicitly
Calling .close() on a paused generator raises GeneratorExit at the suspended yield, allowing finally and active with blocks to clean up. A finally block makes cleanup visible:
def ticker():
try:
n = 0
while True:
yield n
n += 1
finally:
print("cleaned up")
After g = ticker(), two next(g) calls return 0 and 1. Calling g.close() then prints cleaned up; further requests stop.
A generator must not catch GeneratorExit and yield another value: close() then raises RuntimeError. Garbage collection also closes generators, but explicit closing gives prompt cleanup after early stopping. Closing an unstarted generator does not run its body or enter its cleanup block.
Send a value into a paused yield
def averager():
total, count, average = 0, 0, None
while True:
value = yield average
total += value
count += 1
average = total / count
Start with g = averager() and next(g), which yields None and pauses before assigning value. g.send(10) makes that yield expression evaluate to 10, updates the state, and returns the next yielded average, 10.0. Sending 20 returns 15.0; sending 60 returns 30.0.
A new generator must first receive next(g) or g.send(None); sending a non-None value before it starts raises TypeError. Resuming with ordinary next makes the paused yield expression evaluate to None. .throw(exception) instead raises that exception at the pause.
Key Takeaways
yield frompasses through values and receives a generator helper’s return value.- End generator code with
return; escapingStopIterationbecomesRuntimeError. closetriggers cleanup in an active generator.- Start a generator before sending it a non-
Nonevalue. sendsupplies the paused yield expression’s value and returns the next yielded item.throwraises an exception at the paused yield.
5Build and reshape lazy pipelines
A pipeline connects small stages so a final consumer can pull transformed values through them. Built-ins and itertools supply many stages already: joining sources, selecting prefixes, batching records, grouping runs, and generating possible selections. Trace which inputs each stage consumes and what it buffers. Those details determine whether a pipeline can stop early, keep memory bounded, preserve alignment, or safely use an endless source.
5.1 Let the consumer pull through each stage
A pipeline chains stages that accept iterables and produce processed values. The consumer drives the chain: to get one final value, each stage asks the previous one for enough input to produce it.
Build small named stages
def strip_lines(lines):
for line in lines:
yield line.strip()
def drop_blank(lines):
for line in lines:
if line:
yield line
def parse_floats(lines):
for line in lines:
try:
value = float(line)
except ValueError:
continue
yield value
raw = [" 12.5", "", "bad", " 7 ", "3.25"]
total = sum(parse_floats(drop_blank(strip_lines(raw))))
sum asks the parser for a number. The parser asks the blank filter for a string, and that filter asks the stripping stage for a cleaned line. The first input becomes "12.5", passes the filter, converts to 12.5, and reaches sum before the next raw line is read.
The blank input is removed before parsing; "bad" reaches parsing but is skipped after ValueError. The remaining numbers are 7.0 and 3.25, giving total as 22.75. The parser's error policy is explicit: this example deliberately skips invalid numeric strings. A different application might report them.
Combine built-in stages
map transforms, filter selects, enumerate adds a counter, and zip aligns inputs by position. These return iterators. enumerate(lines, start=1) supplies line numbers; reversed(sequence) iterates a reversible sequence backward without making a reversed copy.
Ordinary zip("abc", [1, 2]) stops after [('a', 1), ('b', 2)]. Use strict=True when unequal lengths indicate misaligned records; the mismatch raises ValueError during consumption. Strict zip requires Python 3.10 or newer. Strict multi-input map is available from Python 3.14. Neither option validates all lengths merely by creating the iterator.
Inspect without forgetting consumption
list(islice(stage, 2)) lets you examine two outputs, but those outputs have been consumed. The next request continues after them. Rebuild a pipeline after inspecting it if a later calculation needs the full input, and also recreate an exhausted source or reopen its file.
Check every storage boundary
A pipeline's memory remains bounded only when its source, stages, and consumer each retain bounded data. The example's stages keep a current line or value, so an open file can replace the small list without requiring intermediate lists of all lines. A final list, a sort, a history buffer, or a lagging tee branch changes that storage behavior.
sorted(stage) reads the complete finite stream and returns a list. If only a total and count are needed, maintain those running values instead. A short-circuiting consumer such as next or any can stop early, leaving the upstream iterators partly consumed.
Key Takeaways
- The final consumer pulls values backward through the stage chain.
- Small generator stages make each transformation and error policy visible.
zipstops at the shortest input unless strict checking detects a mismatch.- Inspecting a stage consumes its values.
- Bounded memory requires bounded retention throughout the whole pipeline.
5.2 Choose iterator tools by consumption behavior
The standard-library itertools module supplies small iterator building blocks. Import the functions you use, such as from itertools import islice, chain. They return iterators, but their buffering and stopping rules differ.
Limit, repeat, and join streams
islice(source, start, stop, step) skips and selects positions while advancing the source. list(islice("abcdefg", 2, 6, 2)) gives ['c', 'e']. It accepts no negative indexes and requires a positive step. Taking three values from iter(range(10)) leaves the next value as 3.
count(10, 5) yields 10, 15, 20, 25, and so on. cycle("AB") repeats 'A', 'B' indefinitely; it saves its input values for reuse. repeat("x", 3) yields 'x' three times, and omitting the count repeats forever. repeat reuses the same object; it does not copy a mutable value.
chain([1, 2], (3,), "ab") produces [1, 2, 3, 'a', 'b']. chain.from_iterable([[1, 2], [3], []]) flattens one level from a source of inner iterables without expanding them as separate arguments.
Distinguish a prefix from all matches
With [1, 4, 6, 2, 8] and lambda x: x < 5:
| Tool | Output | Stopping rule |
|---|---|---|
takewhile | [1, 4] | Stop at first failed test |
filter | [1, 4, 2] | Test every input |
dropwhile | [6, 2, 8] | Skip only the initial passing run |
filterfalse | [6, 8] | Keep failed tests throughout |
takewhile consumes the first failing item too: if the source is an iterator, its next item afterward is 2, not 6. dropwhile includes that first failure, then passes all later values without further predicate filtering. compress("ABCD", [1, 0, 1, 1]) selects by a parallel truthy mask and gives ['A', 'C', 'D'].
Align, pair, and batch
zip_longest("abc", [1, 2], fillvalue=0) continues to the longest input and gives [('a', 1), ('b', 2), ('c', 0)]. Padding is useful when unequal lengths are expected; strict zip is useful when they indicate an error.
pairwise([18, 21, 19, 24]) gives overlapping neighbor pairs. Computing b - a gives Celsius changes [3, -2, 5]. For fewer than two inputs, it produces no pairs.
batched(range(7), 3) gives [(0, 1, 2), (3, 4, 5), (6,)] on Python 3.12 or newer. The final tuple may be short. Python 3.13 adds strict=True, which raises ValueError for an incomplete final batch.
Split a stream with tee
left, right = tee(source) provides independently advancing iterators. Use only those returned branches afterward. Advancing the original source bypasses the shared buffering and can skip values for the branches. tee retains items read by a leading branch until lagging branches catch up; a large gap can use substantial memory. Materialize finite data once when independent passes over all values are simpler.
Key Takeaways
isliceselects positions while advancing the source.cyclesaves input values;repeatreuses one object.chain.from_iterableflattens one level lazily.takewhileconsumes its first failing input;dropwhileincludes that input.pairwiseoverlaps neighbors;batchedcreates non-overlapping tuples.teecan buffer many values when its branches advance unevenly.
5.3 Group runs and compute running results
groupby groups consecutive values with the same key. It does not search the entire input for all matching keys. accumulate produces running results, while starmap applies a function to argument tuples.
Group adjacent runs
from itertools import groupby
runs = [(key, len(list(group))) for key, group in groupby("aaabbca")]
runs is [('a', 3), ('b', 2), ('c', 1), ('a', 1)]. The last 'a' forms a separate run because it is not adjacent to the first three. The group is an iterator sharing the underlying input with the outer groupby iterator.
For one group per key, bring equal keys together first:
from operator import itemgetter
sales = [("north", 120), ("south", 80), ("north", 50),
("east", 70), ("south", 30)]
region = itemgetter(0)
totals = {
name: sum(amount for _, amount in group)
for name, group in groupby(sorted(sales, key=region), key=region)
}
Sorting puts east, north, and south runs together. Their sums are 70, 170, and 110, producing {'east': 70, 'north': 170, 'south': 110}. The key used for sorting must make the intended grouping keys adjacent.
Without sorting this input, the region sequence is north, south, north, east, south. A dictionary comprehension overwrites earlier totals for repeated region keys, leaving {'north': 50, 'south': 30, 'east': 70}. For data that cannot be sorted, aggregate into a dictionary while looping.
Consume each group while it is current
Advancing the outer iterator moves the shared source past the previous group. Saving raw group iterators for later therefore loses access to the runs. [list(g) for k, g in list(groupby("aabbb"))] gives [[], []]. Convert each current group immediately, as in {k: list(g) for k, g in groupby("aabbb")}.
A computed key also works. Grouping sorted(["ox", "cat", "be", "dog", "horse"], key=len) by len yields groups of lengths 2, 3, and 5. The stable sort keeps 'ox' before 'be' within the length-two group.
Keep running results
from itertools import accumulate
running = list(accumulate([5, 3, 8, 2]))
peaks = list(accumulate([5, 3, 8, 2], max))
running is [5, 8, 16, 18]; peaks is [5, 5, 8, 8]. With initial=100, addition produces [100, 105, 108, 116, 118], one more result than inputs. functools.reduce combines values into only the final result instead of yielding each intermediate result.
Unpack argument tuples
starmap(pow, [(2, 3), (10, 2)]) calls pow(2, 3) and pow(10, 2), producing [8, 100] when materialized. Use map(pow, [2, 10], [3, 2]) when those arguments arrive in separate streams. Ordinary map(pow, pairs) would pass each tuple as one argument, not unpack it.
Key Takeaways
groupbycollects adjacent equal-key runs, so recurring keys can form separate groups.- Sort by the grouping key for one group per key.
- Consume or store each group before advancing the outer iterator.
accumulateyields running results;initialadds one output.starmapunpacks each input tuple into function arguments.
5.4 Choose arrangements and count their results
Combinatorial iterators produce possible tuples from finite input pools. Choose the operation by asking whether order matters and whether a source position may be reused. Count the expected output before turning a large result into a list.
Product and ordered arrangements
product("AB", [1, 2]) gives [('A', 1), ('A', 2), ('B', 1), ('B', 2)]. The rightmost source advances fastest, just like the inner loop in nested for clauses. The number of tuples is the product of input lengths.
product("01", repeat=3) uses the same pool for three positions and produces eight tuples, from ('0', '0', '0') to ('1', '1', '1'). The outputs are tuples, not strings. Join each one with "".join(bits) when a string is needed.
permutations("ABC", 2) gives ordered selections without reusing positions: AB, AC, BA, BC, CA, CB. With no length argument, it arranges the entire input. For n distinct positions and result length r, where 0 ≤ r ≤ n, the count is:
With n = 3 and r = 2, this is 3 * 2 = 6; arranging all three also gives 3! = 6.
Unordered selections
combinations("ABCD", 2) yields AB, AC, AD, BC, BD, CD. AB and BA represent the same selection, so only the input-order tuple is emitted. The count is:
For four items chosen two at a time, divide 4 * 3 by 2 * 1 to get 6. combinations_with_replacement("AB", 2) adds reuse and gives AA, AB, BB. For a nonempty pool, its count is:
Four items chosen two at a time with reuse give math.comb(5, 2), or 10 results.
| Need | Tool | Count for one pool |
|---|---|---|
| Ordered, reuse allowed | product(pool, repeat=r) | n ** r |
| Ordered, no reused position | permutations(pool, r) | math.perm(n, r) |
| Unordered, no reused position | combinations(pool, r) | math.comb(n, r) |
| Unordered, reuse allowed | combinations_with_replacement(pool, r) | math.comb(n + r - 1, r) |
Distinguish positions from values
Repeated values in the input do not become one source position. permutations("AAB", 2) yields six tuples, but only AA, AB, and BA are distinct by value. set(...) removes duplicates if distinct values are the intended result.
Output follows input position order. combinations("CAB", 2) produces CA, CB, AB, without alphabetically sorting the pool.
Check input storage and output growth
These tools store their finite input pools before producing outputs. product cannot start from an infinite count() input because reading that pool never finishes.
Even small pools can give huge output: 10! is 3,628,800, and product(range(10), repeat=8) yields 100,000,000 tuples. Iterate with an early stop when searching. Use math.perm or math.comb when only the count is needed; math.comb(49, 6) gives 13983816 without generating those selections.
Key Takeaways
- Choose by order and reuse before choosing a combinatorial iterator.
- Product output follows nested-loop order and consists of tuples.
- Permutation and combination functions distinguish input positions.
- Output order follows the pool’s input order.
- These tools pool finite inputs even though they yield outputs lazily.
- Count large result spaces with
math.permormath.comb.
Python Comprehensions and Generators examples
1Turn row data into useful collections
18 steps
- 1IntroductionStart with the desired result
Suppose a script receives rows of measurements and needs several useful views: a cleaned list, a lookup table, and a set of unique labels. A comprehension makes each transformation visible in one expression.
Before choosing syntax, decide whether every input needs a matching output position and whether duplicates should survive. We will start with a list-building loop, then change its conditions and its output shape.
- 2ExampleIdentify the appended value
This loop converts meter readings to centimeters:
meters = [1, 4, 2] centimeters = [] for distance in meters: centimeters.append(distance * 100)The source is
meters; the loop name isdistance; the appended value isdistance * 100. Those three pieces become the comprehension. The loop’s only job is to build a new list, so there is no extra action to preserve. - 3ExplanationMove the value before for
Write the appended value first, followed by the same loop clause:
centimeters = [distance * 100 for distance in meters]Reading
[1, 4, 2]in order produces[100, 400, 200].metersstays unchanged. A comprehension without a filter has one output per input, so three readings should produce three results. Assigning the expression keeps the new list available for later use. - 4ChallengeKeep only the accepted readings
For
meters = [1, 4, 2], write a comprehension that converts only distances greater than1meter to centimeters. What list does it produce?---reveal---
[distance * 100 for distance in meters if distance > 1]gives[400, 200]. The trailing filter rejects1before multiplying. It keeps input order, so the larger value still comes before the smaller one; filtering does not sort the results. - 5ExampleKeep the position when replacing a value
A filter removes positions. A conditional expression changes values while keeping a result for every input:
readings = [6, -2, 0] clipped = [r if r >= 0 else 0 for r in readings]clippedis[6, 0, 0]. The negative reading becomes zero at its existing position. If these entries belong to three fixed measurement times, replacing a value keeps that alignment; removing it would shift later positions. - 6ChallengeChoose the two roles of if
With
readings = [6, -2, 0], a learner wants to keep only nonnegative inputs and writes[r for r in readings if r >= 0 else 0]. Repair the expression and give its result.---reveal---
Use
[r for r in readings if r >= 0], producing[6, 0]. A trailing filter has noelse. The task asks to remove the negative input, so puttingr if r >= 0 else 0at the front would preserve an unwanted extra position. - 7ExampleFlatten rows in loop order
Use the outer row before asking for its values:
rows = [[2, 7], [], [4]] flat = [x for row in rows for x in row]The first row contributes
2and7; the empty row contributes nothing; the last contributes4. The result is[2, 7, 4]. Reversing the two clauses would try to readrowbefore this comprehension has selected it. - 8Key InsightBuild a grid without shared rows
A new list must be built for each mutable row:
grid = [[0] * 2 for _ in range(3)] grid[0][1] = 8The result is
[[0, 8], [0, 0], [0, 0]]. Each outer iteration evaluates[0] * 2again. Writing[[0] * 2] * 3instead repeats references to one row, so changing one cell would appear in every row. The underscore marks an unused loop value. - 9ChallengeChoose flat or nested output
For
rows = [[2, 7], [], [4]], what are the results of[x + 1 for row in rows for x in row]and[[x + 1 for x in row] for row in rows]?---reveal---
The first gives
[3, 8, 5]: each inner value contributes directly to one list. The second gives[[3, 8], [], [5]]: each outer iteration contributes an entire inner list. The empty row survives only in the nested result. - 10TipRecognize a newer flattening form
Python 3.15 allows
[*row for row in rows]for one-level list flattening. It also allows{*group for group in groups}for set union and{**part for part in parts}for merging dictionaries; later values win for repeated keys.On Python 3.14 or earlier, those forms are invalid syntax. The two-clause form
[x for row in rows for x in row]works across the course’s supported versions. - 11ExampleBuild a lookup and a unique-value set
Choose braces with a colon for a lookup:
pairs = [("red", 2), ("blue", 5), ("red", 9)] lookup = {name: value for name, value in pairs} labels = {name for name, value in pairs}lookupis{'red': 9, 'blue': 5}. The later red entry replaces its value, keeping the key’s first position.labelscontains only'red'and'blue'; the set removes duplicates and has no defined order. - 12ChallengeAvoid losing a repeated label
A dictionary maps
"a"and"b"to"warm", and"c"to"cool". What survives when the mapping is inverted with{value: key for key, value in data.items()}? How could all original keys be preserved?---reveal---
The result is
{'warm': 'b', 'cool': 'c'}. The second warm entry replaces the first. To preserve both original keys, use a loop that groups them into lists, such asgrouped.setdefault(value, []).append(key). - 13ExplanationUse hashable members
Dictionary keys and set elements must be hashable. A list cannot serve in either role; a tuple of hashable members can.
points = [[1, 2], [1, 2], [3, 4]] unique = {tuple(point) for point in points}uniquecontains(1, 2)and(3, 4). Usesorted(unique)for a predictable displayed list. Empty braces mean a dictionary;set()is the empty-set constructor. - 14ConnectionChoose a loop for actions and recovery
[print(x) for x in items]builds a list ofNonevalues while printing. A loop makes the action clearer. It also gives a natural place forbreakor per-itemtry/except.If
[int(s) for s in strings]fails at one invalid string, assignment of its new list does not finish. The target keeps its previous binding. A loop can report or skip each failed conversion according to the program’s needs. - 15ExplanationDistinguish loop names from walrus targets
A comprehension loop name stays local, but a walrus target binds in the surrounding scope:
x = "saved" large = [y for x in [1, 2, 3] if (y := x * 4) > 5]largeis[8, 12]; outerxis still'saved';yis12. The assignment expression computes the value once in the filter and makes it available to the front expression. It cannot be placed in the iterable expression afterin. - 16ChallengePredict assignment after a failure
What happens to
valueshere?values = [99] values = [int(text) for text in ["7", "bad", "9"]]---reveal---
Conversion raises
ValueErrorat"bad", andvaluesremains[99]. Assignment happens only after the right-hand expression finishes. If the script needs[7, 9]while skipping invalid strings, an explicit loop with per-item exception handling can implement that policy. - 17ChallengeCombine filtering with normalization
Labels are
[' Oak ', '', 'oak', None, 'Pine']. Build a sorted list of unique, stripped lowercase labels, excludingNoneand blank text.---reveal---
sorted({s.strip().lower() for s in labels if s is not None and s.strip()})gives['oak', 'pine']. The first test protects the string method fromNone; the second removes blank text. The set removes duplicate normalized labels before sorting gives display order. - 18RecapCheck the result shape
For a new task, identify the required result first: positions suggest a list, keyed lookup suggests a dictionary, and unique values suggest a set. Then decide whether missing data should remove a position or occupy it with a replacement.
Trace one accepted input and one rejected input. For nested data, sketch the desired rows before writing the expression; that makes it easier to spot an accidental flattening or shared mutable row.
2Rank records with clear tie rules
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRank full records by one feature
- 2ExamplePass a function to extract the score
- 3Key InsightSave values for later function calls
- 4ChallengeRepair an early call
- 5ExplanationCompute keys once and keep ties stable
- 6ExampleSet directions independently
- 7ChallengeSeparate descending sort from reversal
- 8TipUse stable passes for text directions
- 9ExampleReturn the winner, not its score
- 10ConnectionBuild a small shortlist
- 11ChallengeDistinguish key, value, and pair
- 12ChallengeRepair a ranking plan
- 13RecapChoose the output you need
3Trace loops through a shared stream
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack the position of one pass
- 2ExampleGet an iterator from a source
- 3ExplanationUse exhaustion as a normal signal
- 4ChallengeSeparate lazy sequences from iterators
- 5ExplanationExpand the for loop
- 6ExampleWatch membership consume its match
- 7ChallengeContinue after several consumers
- 8TipKeep mutation away from iteration positions
- 9ExampleStore one countdown position
- 10Key InsightGive every loop fresh progress
- 11ChallengePredict competing nested loops
- 12RecapMark the consumers before tracing
4Follow a generator from creation to cleanup
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionHand control back after one value
- 2ExampleCreate without entering the body
- 3ExplanationResume after the pause
- 4ChallengeSeparate a yield from a return
- 5ExampleKeep only the state the calculation needs
- 6ChallengeStop an endless producer safely
- 7TipKeep the file inside the yielding lifetime
- 8ExamplePass lazy values straight to a consumer
- 9Key InsightSkip work once any knows enough
- 10ChallengeTrack early capture and later lookup
- 11ExampleDelegate to a helper
- 12ExplanationDo not raise the end signal inside the body
- 13ExamplePrime before sending input
- 14ChallengeTrace two sent values
- 15TipClose the active generator
- 16ChallengePredict which delayed error is reached
- 17RecapTrace requests and resource ownership
5Assemble a pipeline and check its boundaries
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDesign from the consumer backward
- 2ExampleName the transformation stages
- 3ConnectionUse alignment checks deliberately
- 4ChallengeAccount for a consumed preview
- 5ExplanationSlice positions or join sources
- 6ExampleChoose repetition and masks
- 7ExplanationCompare prefix operations
- 8ExampleChoose overlap, chunks, or padding
- 9ChallengeTrace the boundary item
- 10Key InsightWatch a tee branch fall behind
- 11ExampleGroup adjacent runs first
- 12ExplanationBring equal keys together
- 13ChallengePreserve groups and totals
- 14ConnectionAccumulate results or unpack arguments
- 15ExplanationChoose by order and reuse
- 16ExampleCount before constructing the output
- 17ChallengeApply both choice rules
- 18TipKeep infinite sources out of input pools
- 19ChallengeFind the storage boundary
- 20RecapAudit inputs, outputs, and retained data
Python Comprehensions and Generators practice questions
Set 1: Read transformations and follow one pass10 Practice Questions
Question 1 of 10
[n + 3 for n in [2, 5, 8]]?Show answerHide answer
3 to each of the three inputs, producing [5, 8, 11]. There is no filter, so the result retains all three positions. Keeping [2, 5, 8] would confuse creating the transformed list with leaving the source list unchanged; the source stays unchanged, but the expression has a new result.Question 2 of 10
None means missing, while zero is valid. What does [x for x in [0, None, 6, -2] if x is not None] produce?Show answerHide answer
None, leaving [0, 6, -2]. Both zero and the negative number pass the stated identity test. The shorter result [6, -2] would come from testing truthiness with if x, which removes valid zero readings as well as missing ones.Question 3 of 10
key to sort strings by length?Show answerHide answer
len itself so the sorter can call it on each string to obtain a comparison key. Writing len() calls the function immediately without a required argument and raises TypeError. str.lower is also a valid key function, but it controls case-insensitive text order instead of string length.Question 4 of 10
sorted([("Uma", 4), ("Eli", 2), ("Bo", 4)], key=lambda row: row[1], reverse=True)?Show answerHide answer
4 records before the 2 record, and stable sorting keeps Uma before Bo. reverse=True changes the direction of key ordering while preserving the original order of ties. Putting Bo first would match reversing the complete ascending result, which also reverses the tied pair.Question 5 of 10
it = iter([9]) and next(it), what does next(it, "empty") return?Show answerHide answer
9, so the iterator is exhausted. The next call returns the explicitly supplied default, "empty". Returning 9 again would require a fresh iterator or source repetition; supplying a default changes exhaustion handling without restarting the existing iterator.Question 6 of 10
What are found and remaining after this code?
it = iter([4, 7, 10, 13])
found = 10 in it
remaining = list(it)
Show answerHide answer
4, 7, and the matching 10, then returns True. The iterator now points to 13, so converting its remainder gives [13]. Keeping 10 in the remainder would treat membership as a peek; iterator membership actually advances through the matching item.Question 7 of 10
What is printed before the final line returns a value?
def produce():
print("ready")
yield 8
g = produce()
value = next(g)
Show answerHide answer
g runs no generator body code. The request in next(g) starts the body, prints ready, and pauses at yield 8, returning 8 into value. Printing twice would confuse creating the generator with starting it; these are separate events, and only the latter executes the print statement.Question 8 of 10
What are first and second?
g = (n * 3 for n in [1, 4])
first = sum(g)
second = sum(g)
Show answerHide answer
sum consumes both generated values, 3 and 12, giving 15. The second call sees an exhausted iterator, and sum of an empty stream is 0. Repeating 15 would be correct for a reusable stored list of the results, but this code saves one generator object.Question 9 of 10
list(zip("wxyz", [6, 9]))?Show answerHide answer
zip pairs values by position and stops when the shortest input ends. There are two numeric inputs, so the result has two pairs. Filling the last two positions with None would require itertools.zip_longest; ordinary zip neither pads missing values nor repeats the shorter input.Question 10 of 10
"DDE" and treats their order as meaningful. How many tuples does permutations("DDE", 2) yield, and how many remain after set(...)?Show answerHide answer
3 * 2 = 6 tuples. Equal letters at different positions create duplicate values; the distinct tuples are DD, DE, and ED. Counting only three yielded tuples would deduplicate the input positions before applying the iterator, which this call does not do.Set 2: Choose shapes, keys, and stopping rules10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
[value for row in [[3, 8], [], [1]] for value in row if value < 5]?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
{name.lower(): score for name, score in [("Ray", 7), ("RAY", 9), ("Ivo", 5)]}?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
words = ["ant", "wolf", "lynx", "ox"], what does max(words, key=len) return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What is result?
funcs = [lambda: n + 1 for n in range(2, 5)]
result = [f() for f in funcs]
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
__next__ method do when no values remain?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What does remaining contain?
it = iter([2, 4, 6, 8, 10])
a = next(it)
found = 6 in it
remaining = list(it)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
When does this code raise ValueError?
def values(limit):
if limit < 0:
raise ValueError("negative limit")
yield limit
g = values(-2)
next(g)
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is list(outer())?
def inner():
yield "x"
return 4
def outer():
total = yield from inner()
yield total + 1
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
list(batched("JKLMN", 2)) on Python 3.12? Assume batched is imported from itertools.Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
[(k, len(list(g))) for k, g in groupby("rrsrr")]? Assume groupby is imported.Show answerHide answer
Save this lesson to see this answer.
Set 3: Diagnose scope and shared state10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What is outside after this code?
outside = "keep"
values = [outside * 2 for outside in [1, 3]]
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is result?
raw = [None, "", " ivy ", "oak"]
result = [s.strip() if s else "missing"
for s in raw if s is not None]
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
(name, score) records with numeric scores?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
stock = {"bolts": 14, "clips": 25, "washers": 9}, what is max(stock, key=stock.get)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What are a and b?
source = [11, 22]
left = iter(source)
right = iter(source)
a = next(left)
b = next(right)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
self from __iter__ and yields 1, 2, 3 from successive __next__ calls. For a fresh instance c, what is [(a, b) for a in c for b in c]?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What does list(g) return?
data = [2, 5]
factor = 4
g = (x * factor for x in data)
data = [9]
factor = 3
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is list(items())?
def items():
yield 6
return 12
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What are prefix and remaining?
from itertools import takewhile
it = iter([3, 5, 9, 4, 12])
prefix = list(takewhile(lambda n: n < 8, it))
remaining = list(it)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
list(zip(["a", "b", "c"], [2, 4], strict=True)) is evaluated?Show answerHide answer
Save this lesson to see this answer.
Set 4: Trace delayed work across several stages10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
rows = [[0] * 2] * 2 and rows[0][1] = 7?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What are result and y after this code?
y = 99
result = [y for x in [2, 3, 4] if (y := x * 3) > 8]
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[(f()) for f in [lambda n=n: n * 2 for n in range(3, 6)]]?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
[("Ari", 5), ("Zoe", 3), ("Tao", 5), ("Bea", 3)], what two-pass plan produces [("Zoe", 3), ("Bea", 3), ("Tao", 5), ("Ari", 5)]?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What is result?
it = iter([1, 0, 5, 7])
a = all(it)
b = next(it)
result = (a, b, list(it))
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What is result?
def running():
total = 0
while True:
value = yield total
total += value
g = running()
a = next(g)
b = g.send(4)
c = g.send(9)
result = (a, b, c)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
with open(path) as f: and returns (line.strip() for line in f). Why does consuming its returned object fail?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
What is totals?
from itertools import groupby
rows = [("p", 2), ("q", 7), ("p", 5)]
totals = {k: sum(n for _, n in g)
for k, g in groupby(rows, key=lambda row: row[0])}
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
list(starmap(pow, [(3, 2), (2, 5)])) return? Assume starmap is imported from itertools.Show answerHide answer
Save this lesson to see this answer.
Set 5: Reason about complete pipeline behavior10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
normalized = ["mint", "mint", "sage", "sage"], what is len(set(normalized))?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What is result?
rows = [[1, 4], [2, 5]]
result = [(i, x) for i, row in enumerate(rows)
for x in row if x > i + 2]
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
heapq.nsmallest(2, [("Rio", 8), ("Kit", 3), ("Sol", 6)], key=lambda r: r[1]) return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
self.start = 2. Its __iter__ sets local n = self.start, yields while n > 0, and decrements local n. What is [(a, b) for a in c for b in c]?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
What happens when list(broken()) is evaluated?
def broken():
yield 2
next(iter([]))
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What are len(history) and history[-1] after this code?
from itertools import islice
def record_stream(history):
for n in range(100):
record = [n]
history.append(record)
yield record
history = []
g = record_stream(history)
preview = list(islice(g, 3))
del preview
next(g)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What is result?
from itertools import islice
raw = [" 2 ", "", "5", " 8 "]
clean = (s.strip() for s in raw)
nums = (int(s) for s in clean if s)
preview = list(islice(nums, 1))
result = (preview, sum(nums))
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Which previously produced values does right still need from the tee buffer, and what will next(left) return?
from itertools import tee, islice
left, right = tee(iter(range(8)))
a = list(islice(left, 5))
b = next(right)
c = list(islice(right, 2))
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What is result?
from itertools import groupby
saved = list(groupby("hhj"))
result = [list(group) for _, group in saved]
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
list(combinations_with_replacement("RS", 2))? Assume the function is imported.Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulation
accumulate.max yields the greatest reading seen so far after each new reading.Assignment expression
:= to bind a value while evaluating an expression, making that computed value available for reuse.B
Batching
Bounded memory
C
Callable
len can be passed directly to a sorter without evaluating len() first.Cartesian product
Case folding
str.casefold treats the German string "Straße" as "strasse" for comparison.Chaining
chain or chain.from_iterable.Combination
Combination with replacement
Comprehension filter
if clause that decides whether an input reaches the result expression.Comprehension scope
x after a list is built using x as its loop name.Conditional expression
a if condition else b, evaluating only the chosen branch.Consecutive run
groupby.Consumer
any can leave part of a shared iterator unread after finding a truthy value.D
Default parameter
lambda n=n: n saves the current loop value for that particular function.Default result
min or max form when that iterable contains no items.max(data, default=None) is not compared against any actual data.Delegation
yield from forwards values from another iterable and can receive a sub-generator’s final return value.Dictionary comprehension
Duplicate key
E
Eager evaluation
any begins inspecting that list.Exhaustion
list call on the same consumed generator returns an empty list.Extreme selection
max(records, key=...) returns a complete record, not just its comparison score.F
Flattening
for clauses keeps their values in row-by-row order.G
Generator expression
sum without building an intermediate list.Generator function
yield in its body and returns a generator object when called, delaying execution of that body.Generator object
next before a loop continues it.GeneratorExit
close().Groupby
groupby iterator yields a key and a shared-source iterator for each consecutive run of equal-key values.H
Hashability
I
In-place sort
.sort() and returns None, instead of returning a new sorted list.None.Infinite generator
islice prefix.Input pool
product can begin producing its lazy output.Insertion order
Iterable
iter(), providing values through the iterator returned for a pass through it.Iteration order
Iterator
next() and returns itself from iter(), retaining the current progress of one pass.Iterator protocol
__iter__ to return the iterator and __next__ to supply a value or raise StopIteration.for, sum, and list.Iterator slice
islice, consuming skipped inputs while accepting no negative indexes or nonpositive step.Iterator state
K
Key function
len orders words by length without replacing the words with numbers.L
Lambda expression
Late binding
Lazy evaluation
Lazy sequence
range(10) can be reused even though it does not store all ten integers as a list.Leftmost iterable
in in a generator expression, whose iterator is obtained at creation.List comprehension
M
Mask selection
compress does.compress keeps only the names whose matching selector is truthy.Materialization
list(map(...)) makes the transformed values available for repeated access.Multi-pass sort
N
Nested comprehension
O
Outer loop
for.P
Pairwise iteration
Permutation
Pipeline
Prefix selection
takewhile does.Priming
next() or send(None) so it reaches a yield that can receive a later sent value.R
Rebinding
Reduction
functools.reduce does without yielding intermediate results.accumulate would expose the running values.Resource lifetime
with block until completion or explicit close.Result expression
name.upper() converts each accepted name into uppercase text.Retained state
Reusable iterable
S
Send
send method resumes a generator, supplies the paused yield expression’s value, and returns the next value yielded.Sequence protocol
__getitem__ at indexes starting from zero until IndexError signals the end.iter() without an explicit __iter__ method.Set comprehension
Shared reference
Short-circuit evaluation
Short-circuiting consumer
any after a truthy value.Side effect
Single-pass iteration
Snapshot
Stable sort
Stage
Starmap
starmap iterator unpacks each input tuple into separate positional arguments when it calls the supplied function.pow without a custom unpacking function.Starred unpacking
first, *rest = source gathers every remaining value into rest.StopIteration
for loop handles as normal completion.Strict zip
zip(..., strict=True), which raises ValueError during consumption when the input lengths differ.Suspension
T
Tee buffer
Throw
throw method resumes a generator by raising a supplied exception at its paused yield, where generator code may handle it.ValueError("bad input") makes that exception arise at the generator’s suspended yield.Top-n selection
heapq.nlargest is useful for a small shortlist from many records.Transposition
Truthiness
None, and empty containers are falsy.None.Tuple key
Tuple unpacking
for name, count in stock.items() gives the key and value separate names.U
Unpacking comprehension
* or **, from Python 3.15.[*row for row in rows] collects all row elements into one list.Y
Yield
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.