Python Comprehensions and Generators: Iterators and Lambda

Write compact, readable Python for transforming data. Build lists, dictionaries and sets with comprehensions, sort and select items with key functions and 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

  1. 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 comprehension
      Read 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 value
      Tell a trailing if, which drops items, from if ... else before for, which changes items, and combine several conditions correctly.
    • Write nested comprehensions
      Use several for clauses 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 comprehensions
      Write {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 tool
      Weigh readability, side effects and scope: know where comprehension variables live, when the walrus operator helps, and when a loop, map or filter is clearer.
  2. Pass small functions to sorted, min, max and similar tools to control how items are compared, and write them inline with lambda where that keeps code clear.
    • Write lambda expressions
      Write anonymous one-expression functions with lambda, compare them with def, pass functions without calling them, and avoid the late-binding trap.
    • Sort with sorted, list.sort and key functions
      Sort 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 functions
      Use min, max, heapq.nlargest and sorted slices with a key to find the best, worst and top few items, including ties and empty inputs.
  3. Describe the iterator protocol behind every for loop, predict when an iterator is used up, and write classes that work in for loops.
    • Tell iterables and iterators apart
      Define iterables and iterators, step through an iterator with iter() and next(), and recognize which common objects are which.
    • Trace how a for loop consumes an iterator
      Rewrite a for loop with iter() and next(), predict what happens when an iterator is reused, and avoid changing a collection while looping over it.
    • Implement the iterator protocol in a class
      Write an iterator class with __iter__ and __next__, and an iterable class that hands out a fresh iterator for every loop.
  4. 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 yield
      Write functions that yield values, trace how a generator pauses and resumes, and know what calling a generator function actually returns.
    • Produce data lazily and work with infinite sequences
      Use 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 expressions
      Write lazy one-line generators with parentheses, pass them straight to functions such as sum and any, and choose between a generator expression and a list comprehension.
    • Delegate to sub-generators and control running generators
      Use yield from to delegate, return a final value, end a generator correctly, and use close() and send() on a running generator.
  5. Connect generators, built-in iterator functions and the itertools module into pipelines that process data step by step without building intermediate lists.
    • Chain generator stages into a pipeline
      Build 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 itertools
      Use islice, count, cycle, repeat, chain, takewhile, dropwhile, filterfalse, compress, zip_longest, pairwise, batched and tee to reshape iterators lazily.
    • Group, accumulate and map with itertools
      Summarize streams with groupby and accumulate, apply functions to tuples with starmap, and avoid the classic groupby mistakes.
    • Generate products, permutations and combinations
      Replace nested loops with itertools.product, list arrangements and selections with permutations and combinations, and predict how many results each produces.

Python Comprehensions and Generators study guide

5 chapters

1

Build 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 for clause.
  • 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.

JobPositionEffect
FilterAfter the for clauseKeeps or drops the input
Conditional valueBefore for, with elseChooses 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 if removes inputs; a if condition else b chooses 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 for clauses 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'].

ResultKeeps duplicates?Access pattern
ListYesPosition and iteration order
DictionaryOne value per keyLookup by key
SetNoMembership 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 and tuple(...) to build a tuple.
  • Use Counter for 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.
  • map and filter return lazy iterators in Python 3.
2

Sort 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 def when 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:

ExpressionResult
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

  • sorted returns a new list; .sort() changes a list and returns None.
  • 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

  • min and max return original items and keep the first best-key tie.
  • Use default for empty inputs in the single-iterable form.
  • Choose dictionary keys, values, or value-ranked keys deliberately.
  • nlargest and nsmallest return ranked lists and retain duplicates.
3

Follow 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.

ObjectReusable data or sequence?Direct next()?
ListYesNo
rangeYesNo
List iteratorOne passYes
Generator objectOne passYes
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 with StopIteration.
  • Each list iterator has its own position.
  • range is lazy and reusable, while generators are single-pass.
  • Calling iter is 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 self from __iter__ and advance in __next__.
  • Raise StopIteration at the end; None is an ordinary value.
  • Reusable iterable classes provide fresh iterator state for each pass.
  • A generator __iter__ method creates fresh local state on each call.
4

Produce 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.

StatementEffect in a generator
yield valueSupplies one item and pauses
return valueEnds the stream with a final return value
End of bodyEnds 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.
  • next resumes after the previous yield and runs to the next one.
  • Local variables and execution position survive each pause.
  • return ends 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, and next can 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 from passes through values and receives a generator helper’s return value.
  • End generator code with return; escaping StopIteration becomes RuntimeError.
  • close triggers cleanup in an active generator.
  • Start a generator before sending it a non-None value.
  • send supplies the paused yield expression’s value and returns the next yielded item.
  • throw raises an exception at the paused yield.
5

Build 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.
  • zip stops 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:

ToolOutputStopping 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

  • islice selects positions while advancing the source.
  • cycle saves input values; repeat reuses one object.
  • chain.from_iterable flattens one level lazily.
  • takewhile consumes its first failing input; dropwhile includes that input.
  • pairwise overlaps neighbors; batched creates non-overlapping tuples.
  • tee can 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

  • groupby collects 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.
  • accumulate yields running results; initial adds one output.
  • starmap unpacks 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:

n!(n−r)!

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:

(nr)=n!r!(n−r)!

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:

(n+r−1r)

Four items chosen two at a time with reuse give math.comb(5, 2), or 10 results.

NeedToolCount for one pool
Ordered, reuse allowedproduct(pool, repeat=r)n ** r
Ordered, no reused positionpermutations(pool, r)math.perm(n, r)
Unordered, no reused positioncombinations(pool, r)math.comb(n, r)
Unordered, reuse allowedcombinations_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.perm or math.comb.

Python Comprehensions and Generators examples

5 Walkthroughs

1

Turn row data into useful collections

18 steps
Build and trace comprehensions, choose the result shape, and repair common scope and sharing mistakes.
  1. 1
    IntroductionStart 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.

  2. 2
    ExampleIdentify 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 is distance; the appended value is distance * 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.

  3. 3
    ExplanationMove 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]. meters stays 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.

  4. 4
    ChallengeKeep only the accepted readings

    For meters = [1, 4, 2], write a comprehension that converts only distances greater than 1 meter to centimeters. What list does it produce?

    ---reveal---

    [distance * 100 for distance in meters if distance > 1] gives [400, 200]. The trailing filter rejects 1 before multiplying. It keeps input order, so the larger value still comes before the smaller one; filtering does not sort the results.

  5. 5
    ExampleKeep 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]
    

    clipped is [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.

  6. 6
    ChallengeChoose 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 no else. The task asks to remove the negative input, so putting r if r >= 0 else 0 at the front would preserve an unwanted extra position.

  7. 7
    ExampleFlatten 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 2 and 7; the empty row contributes nothing; the last contributes 4. The result is [2, 7, 4]. Reversing the two clauses would try to read row before this comprehension has selected it.

  8. 8
    Key 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] = 8
    

    The result is [[0, 8], [0, 0], [0, 0]]. Each outer iteration evaluates [0] * 2 again. Writing [[0] * 2] * 3 instead repeats references to one row, so changing one cell would appear in every row. The underscore marks an unused loop value.

  9. 9
    ChallengeChoose 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.

  10. 10
    TipRecognize 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.

  11. 11
    ExampleBuild 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}
    

    lookup is {'red': 9, 'blue': 5}. The later red entry replaces its value, keeping the key’s first position. labels contains only 'red' and 'blue'; the set removes duplicates and has no defined order.

  12. 12
    ChallengeAvoid 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 as grouped.setdefault(value, []).append(key).

  13. 13
    ExplanationUse 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}
    

    unique contains (1, 2) and (3, 4). Use sorted(unique) for a predictable displayed list. Empty braces mean a dictionary; set() is the empty-set constructor.

  14. 14
    ConnectionChoose a loop for actions and recovery

    [print(x) for x in items] builds a list of None values while printing. A loop makes the action clearer. It also gives a natural place for break or per-item try/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.

  15. 15
    ExplanationDistinguish 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]
    

    large is [8, 12]; outer x is still 'saved'; y is 12. 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 after in.

  16. 16
    ChallengePredict assignment after a failure

    What happens to values here?

    values = [99]
    values = [int(text) for text in ["7", "bad", "9"]]
    

    ---reveal---

    Conversion raises ValueError at "bad", and values remains [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.

  17. 17
    ChallengeCombine filtering with normalization

    Labels are [' Oak ', '', 'oak', None, 'Pine']. Build a sorted list of unique, stripped lowercase labels, excluding None and 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 from None; the second removes blank text. The set removes duplicate normalized labels before sorting gives display order.

  18. 18
    RecapCheck 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.

2

Rank records with clear tie rules

13 steps
Work through key extraction, stable ordering, and choosing an item or a ranked subset.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRank full records by one feature
  2. 2
    ExamplePass a function to extract the score
  3. 3
    Key InsightSave values for later function calls
  4. 4
    ChallengeRepair an early call
  5. 5
    ExplanationCompute keys once and keep ties stable
  6. 6
    ExampleSet directions independently
  7. 7
    ChallengeSeparate descending sort from reversal
  8. 8
    TipUse stable passes for text directions
  9. 9
    ExampleReturn the winner, not its score
  10. 10
    ConnectionBuild a small shortlist
  11. 11
    ChallengeDistinguish key, value, and pair
  12. 12
    ChallengeRepair a ranking plan
  13. 13
    RecapChoose the output you need
3

Trace loops through a shared stream

12 steps
See where an iterator keeps its position, then design classes for single or repeated passes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack the position of one pass
  2. 2
    ExampleGet an iterator from a source
  3. 3
    ExplanationUse exhaustion as a normal signal
  4. 4
    ChallengeSeparate lazy sequences from iterators
  5. 5
    ExplanationExpand the for loop
  6. 6
    ExampleWatch membership consume its match
  7. 7
    ChallengeContinue after several consumers
  8. 8
    TipKeep mutation away from iteration positions
  9. 9
    ExampleStore one countdown position
  10. 10
    Key InsightGive every loop fresh progress
  11. 11
    ChallengePredict competing nested loops
  12. 12
    RecapMark the consumers before tracing
4

Follow a generator from creation to cleanup

17 steps
Trace yields, delayed calculations, delegation, and values sent into a running generator.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionHand control back after one value
  2. 2
    ExampleCreate without entering the body
  3. 3
    ExplanationResume after the pause
  4. 4
    ChallengeSeparate a yield from a return
  5. 5
    ExampleKeep only the state the calculation needs
  6. 6
    ChallengeStop an endless producer safely
  7. 7
    TipKeep the file inside the yielding lifetime
  8. 8
    ExamplePass lazy values straight to a consumer
  9. 9
    Key InsightSkip work once any knows enough
  10. 10
    ChallengeTrack early capture and later lookup
  11. 11
    ExampleDelegate to a helper
  12. 12
    ExplanationDo not raise the end signal inside the body
  13. 13
    ExamplePrime before sending input
  14. 14
    ChallengeTrace two sent values
  15. 15
    TipClose the active generator
  16. 16
    ChallengePredict which delayed error is reached
  17. 17
    RecapTrace requests and resource ownership
5

Assemble a pipeline and check its boundaries

20 steps
Process a stream, reshape it with iterator tools, and reason about grouping, buffering, and result counts.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDesign from the consumer backward
  2. 2
    ExampleName the transformation stages
  3. 3
    ConnectionUse alignment checks deliberately
  4. 4
    ChallengeAccount for a consumed preview
  5. 5
    ExplanationSlice positions or join sources
  6. 6
    ExampleChoose repetition and masks
  7. 7
    ExplanationCompare prefix operations
  8. 8
    ExampleChoose overlap, chunks, or padding
  9. 9
    ChallengeTrace the boundary item
  10. 10
    Key InsightWatch a tee branch fall behind
  11. 11
    ExampleGroup adjacent runs first
  12. 12
    ExplanationBring equal keys together
  13. 13
    ChallengePreserve groups and totals
  14. 14
    ConnectionAccumulate results or unpack arguments
  15. 15
    ExplanationChoose by order and reuse
  16. 16
    ExampleCount before constructing the output
  17. 17
    ChallengeApply both choice rules
  18. 18
    TipKeep infinite sources out of input pools
  19. 19
    ChallengeFind the storage boundary
  20. 20
    RecapAudit inputs, outputs, and retained data

Python Comprehensions and Generators practice questions

50 Practice Questions in 5 sets

Set 1: Read transformations and follow one pass10 Practice Questions

Question 1 of 10

What is the value of [n + 3 for n in [2, 5, 8]]?
  1. [2, 5, 8]
  2. [3, 6, 9]
  3. [5, 8, 11]
  4. [5, 8]
Show answerHide answer
Answer: C
The comprehension adds 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

A reading of None means missing, while zero is valid. What does [x for x in [0, None, 6, -2] if x is not None] produce?
  1. [0, 6, 0]
  2. [6, -2]
  3. [0, None, 6, -2]
  4. [0, 6, -2]
Show answerHide answer
Answer: D
The filter removes only the input equal to 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

What function can you pass as key to sort strings by length?
  1. len()
  2. str
  3. str.lower
  4. len
Show answerHide answer
Answer: D
Pass 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

What is sorted([("Uma", 4), ("Eli", 2), ("Bo", 4)], key=lambda row: row[1], reverse=True)?
  1. [("Bo", 4), ("Uma", 4), ("Eli", 2)]
  2. [("Uma", 4), ("Bo", 4), ("Eli", 2)]
  3. [("Eli", 2), ("Uma", 4), ("Bo", 4)]
  4. [("Uma", 4), ("Eli", 2), ("Bo", 4)]
Show answerHide answer
Answer: B
Descending key order puts both 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

After it = iter([9]) and next(it), what does next(it, "empty") return?
  1. None
  2. 9
  3. "empty"
  4. []
Show answerHide answer
Answer: C
The first request consumes the only value, 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)
  1. True and [13]
  2. True and [10, 13]
  3. True and [4, 7, 10, 13]
  4. False and []
Show answerHide answer
Answer: A
The search consumes 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)
  1. Nothing is printed.
  2. ready is printed twice.
  3. 8 is printed once.
  4. ready is printed once.
Show answerHide answer
Answer: D
Creating 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)
  1. 15 and 15
  2. 15 and 0
  3. 3 and 12
  4. 0 and 15
Show answerHide answer
Answer: B
The first 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

What is list(zip("wxyz", [6, 9]))?
  1. [("w", 6), ("x", 6), ("y", 9), ("z", 9)]
  2. [("w", 6), ("x", 9), ("y", None), ("z", None)]
  3. [("w", 6), ("x", 9)]
  4. [("w", 6), ("x", 9), ("y", 6), ("z", 9)]
Show answerHide answer
Answer: C
Ordinary 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

A test chooses two distinct positions from "DDE" and treats their order as meaningful. How many tuples does permutations("DDE", 2) yield, and how many remain after set(...)?
  1. 6 yielded; 3 distinct
  2. 6 yielded; 6 distinct
  3. 3 yielded; 3 distinct
  4. 9 yielded; 4 distinct
Show answerHide answer
Answer: A
There are three source positions, so choosing an ordered pair without position reuse gives 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

What is [value for row in [[3, 8], [], [1]] for value in row if value < 5]?
  1. [[3], [], [1]]
  2. [1, 3]
  3. [3, 8, 1]
  4. [3, 1]
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What is {name.lower(): score for name, score in [("Ray", 7), ("RAY", 9), ("Ivo", 5)]}?
  1. {"ray": [7, 9], "ivo": 5}
  2. {"ray": 9, "ivo": 5}
  3. {"Ray": 7, "RAY": 9, "Ivo": 5}
  4. {"ray": 7, "ivo": 5}
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For words = ["ant", "wolf", "lynx", "ox"], what does max(words, key=len) return?
  1. "wolf"
  2. 4
  3. "lynx"
  4. "ox"
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]
  1. [5, 5, 5]
  2. [4, 4, 4]
  3. [3, 4, 5]
  4. [2, 3, 4]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What should an iterator’s __next__ method do when no values remain?
  1. Return None.
  2. Return self.
  3. Raise StopIteration.
  4. Raise IndexError.
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)
  1. [6, 8, 10]
  2. [4, 8, 10]
  3. [2, 4, 8, 10]
  4. [8, 10]
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)
  1. During g = values(-2).
  2. During next(g).
  3. During the function definition.
  4. It returns -2 without an error.
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
  1. ["x", 4, 5]
  2. [4, 5]
  3. ["x", 5]
  4. ["x", None]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What is list(batched("JKLMN", 2)) on Python 3.12? Assume batched is imported from itertools.
  1. [("J", "K"), ("L", "M"), ("N",)]
  2. [("J", "K"), ("K", "L"), ("L", "M"), ("M", "N")]
  3. [("J", "K"), ("L", "M")]
  4. [("J", "K"), ("L", "M"), ("N", None)]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What is [(k, len(list(g))) for k, g in groupby("rrsrr")]? Assume groupby is imported.
  1. [("r", 4), ("s", 1)]
  2. [("r", 2), ("s", 1)]
  3. [("r", 1), ("s", 1), ("r", 1)]
  4. [("r", 2), ("s", 1), ("r", 2)]
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]]
  1. 3
  2. "keep"
  3. 6
  4. [2, 6]
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]
  1. ["ivy", "oak"]
  2. ["missing", "missing", "ivy", "oak"]
  3. ["", "ivy", "oak"]
  4. ["missing", "ivy", "oak"]
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Records must be ordered by score descending, then name ascending. What key gives that order for (name, score) records with numeric scores?
  1. lambda row: (row[1], row[0])
  2. lambda row: (row[0], -row[1])
  3. lambda row: (-row[1], row[0])
  4. lambda row: (-row[1], -row[0])
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For stock = {"bolts": 14, "clips": 25, "washers": 9}, what is max(stock, key=stock.get)?
  1. "clips"
  2. 25
  3. "washers"
  4. ("clips", 25)
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)
  1. 11 and 22
  2. 11 and 11
  3. 22 and 11
  4. 22 and 22
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A class returns 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]?
  1. [(1, 2), (1, 3)]
  2. [(1, 1), (2, 2), (3, 3)]
  3. [(1, 1), (1, 2), (1, 3)]
  4. [(1, 2), (2, 3)]
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
  1. [27]
  2. [8, 20]
  3. [36]
  4. [6, 15]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What is list(items())?

def items():
    yield 6
    return 12
  1. [6, 12]
  2. [12]
  3. [6]
  4. [6, None]
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)
  1. [3, 5, 4] and [9, 12]
  2. [3, 5] and [9, 4, 12]
  3. [3, 5] and [4, 12]
  4. [3, 5, 4] and [12]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What happens when list(zip(["a", "b", "c"], [2, 4], strict=True)) is evaluated?
  1. It returns two pairs and ignores "c".
  2. It raises ValueError during consumption.
  3. It returns three pairs, padding with None.
  4. It raises TypeError before iteration.
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

What happens after rows = [[0] * 2] * 2 and rows[0][1] = 7?
  1. rows is [[0, 7], [0, 7]].
  2. rows is [[0, 0], [0, 7]].
  3. rows is [[7, 0], [7, 0]].
  4. rows is [[0, 7], [0, 0]].
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]
  1. [9, 12] and 99
  2. [6, 9, 12] and 12
  3. [9, 12] and 12
  4. [99, 99] and 12
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What is [(f()) for f in [lambda n=n: n * 2 for n in range(3, 6)]]?
  1. [6, 6, 6]
  2. [10, 10, 10]
  3. [3, 4, 5]
  4. [6, 8, 10]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Names must be descending within each ascending score group. For records [("Ari", 5), ("Zoe", 3), ("Tao", 5), ("Bea", 3)], what two-pass plan produces [("Zoe", 3), ("Bea", 3), ("Tao", 5), ("Ari", 5)]?
  1. Sort score ascending, then name descending.
  2. Sort name descending, then score ascending.
  3. Sort name ascending, then score ascending.
  4. Sort score descending, then name ascending.
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))
  1. (False, 0, [5, 7])
  2. (True, 7, [])
  3. (False, 1, [0, 5, 7])
  4. (False, 5, [7])
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)
  1. (None, 4, 13)
  2. (0, 4, 9)
  3. (0, 4, 13)
  4. (0, None, None)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An ordinary function enters with open(path) as f: and returns (line.strip() for line in f). Why does consuming its returned object fail?
  1. The file has already been closed.
  2. A file is not an iterable source.
  3. strip requires the entire file as one string.
  4. Generator expressions cannot return strings.
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])}
  1. {"p": 7, "q": 7}
  2. {"p": 5, "q": 7}
  3. {"p": 2, "q": 7}
  4. {"p": [2, 5], "q": [7]}
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A search needs ordered triples with no reused position from six distinct labels, but only the count is needed. What calculation gives the result without generating tuples?
  1. math.comb(6, 3) gives 20.
  2. math.perm(6, 3) gives 120.
  3. math.comb(8, 3) gives 56.
  4. 6 ** 3 gives 216.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What does list(starmap(pow, [(3, 2), (2, 5)])) return? Assume starmap is imported from itertools.
  1. [6, 10]
  2. [3, 2, 2, 5]
  3. [8, 25]
  4. [9, 32]
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

For normalized = ["mint", "mint", "sage", "sage"], what is len(set(normalized))?
  1. 1
  2. 3
  3. 2
  4. 4
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]
  1. [(0, 4), (1, 2), (1, 5)]
  2. [(0, 4), (1, 5)]
  3. [(1, 4), (2, 5)]
  4. [(0, 1), (0, 4), (1, 2), (1, 5)]
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does heapq.nsmallest(2, [("Rio", 8), ("Kit", 3), ("Sol", 6)], key=lambda r: r[1]) return?
  1. [("Kit", 3), ("Sol", 6)]
  2. [("Rio", 8), ("Sol", 6)]
  3. [3, 6]
  4. [("Sol", 6), ("Kit", 3)]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A reusable countdown stores 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]?
  1. [(2, 1)]
  2. [(2, 2), (1, 1)]
  3. [(2, 2), (2, 1)]
  4. [(2, 2), (2, 1), (1, 2), (1, 1)]
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([]))
  1. It returns [2] normally.
  2. It raises RuntimeError.
  3. It returns [2, None].
  4. It raises StopIteration directly.
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)
  1. 3 and [2]
  2. 1 and [3]
  3. 4 and [3]
  4. 4 and [4]
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))
  1. ([2], 8)
  2. ([2], 15)
  3. ([2], 0)
  4. ([2], 13)
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))
  1. [3, 4] and 5
  2. [0, 1, 2, 3, 4] and 5
  3. [3, 4] and 3
  4. [3, 4, 5] and 6
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]
  1. [["h", "h"], ["j"]]
  2. [["h"], ["j"]]
  3. [[], []]
  4. [["h", "h", "j"]]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What is list(combinations_with_replacement("RS", 2))? Assume the function is imported.
  1. [("R", "R"), ("R", "S"), ("S", "S")]
  2. [("R", "S"), ("S", "R")]
  3. [("R", "R"), ("R", "S"), ("S", "R"), ("S", "S")]
  4. [("R", "S")]
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

88 Key Terms, each with its definition

A

Accumulation
Accumulation combines each new input with a running result and yields the successive results through accumulate.
Accumulation with max yields the greatest reading seen so far after each new reading.
Assignment expression
An assignment expression uses := to bind a value while evaluating an expression, making that computed value available for reuse.
An assignment expression can strip a line once and reuse the cleaned text after checking it.

B

Batching
Batching groups a stream into non-overlapping tuples of a chosen size, allowing a shorter final tuple unless strict checking rejects it.
Batching records into groups of 100 can prepare chunks for a service without storing the entire stream.
Bounded memory
Bounded memory means retained storage has a fixed bound as more input is processed, requiring bounded retention throughout a pipeline.
Bounded memory is lost if the consumer stores every output in a list, even when upstream stages are lazy.

C

Callable
A callable is an object that can be invoked with parentheses; a key argument needs a callable that accepts one item.
The callable len can be passed directly to a sorter without evaluating len() first.
Cartesian product
A Cartesian product selects one value from each input pool in ordered positions, matching nested-loop combinations of those pools.
A Cartesian product can pair every test size with every available test mode.
Case folding
Case folding converts text into a form useful for case-insensitive comparison, handling more distinctions than lowercase conversion.
Case folding with str.casefold treats the German string "Straße" as "strasse" for comparison.
Chaining
Chaining joins iterables in sequence, exhausting one before reading the next, using chain or chain.from_iterable.
Chaining daily batches lets one consumer read their records as a continuous stream.
Combination
A combination is a selection without position reuse in which order does not distinguish results, so only input-order tuples are emitted.
A combination selects a two-person team without also listing the same team in reverse order.
Combination with replacement
A combination with replacement permits an input position to be selected repeatedly while still treating selection order as irrelevant.
A combination with replacement can select two samples from named types when repeated types are allowed.
Comprehension filter
A comprehension filter is a trailing if clause that decides whether an input reaches the result expression.
A comprehension filter can skip zero denominators before Python evaluates a division.
Comprehension scope
Comprehension scope keeps its loop variables separate from surrounding bindings while allowing the expression to read outer names.
Comprehension scope preserves an existing outer x after a list is built using x as its loop name.
Conditional expression
A conditional expression chooses between two result values using a if condition else b, evaluating only the chosen branch.
A conditional expression can replace a missing measurement while preserving its position.
Consecutive run
A consecutive run is an uninterrupted stretch of inputs with the same grouping key, ending when that key changes.
A consecutive run of matching labels becomes one group under groupby.
Consumer
A consumer requests values from an iterable to process them, store them, or decide a result, sometimes stopping before exhaustion.
The consumer any can leave part of a shared iterator unread after finding a truthy value.

D

Default parameter
A default parameter has a value evaluated at function creation and used when the caller omits that argument.
A default parameter in lambda n=n: n saves the current loop value for that particular function.
Default result
A default result is the fallback returned by the single-iterable min or max form when that iterable contains no items.
The default result in max(data, default=None) is not compared against any actual data.
Delegation
Delegation through yield from forwards values from another iterable and can receive a sub-generator’s final return value.
Delegation lets a report generator pass through numbered items before using their final count.
Dictionary comprehension
A dictionary comprehension builds a new dictionary from key and value expressions separated by a colon, with optional filters.
A dictionary comprehension can map each sensor name to its latest stored reading.
Duplicate key
A duplicate key is a key produced again for an existing dictionary entry, causing the later value to replace the earlier value.
A duplicate key can discard an earlier name when a dictionary is inverted using repeated values.

E

Eager evaluation
Eager evaluation performs the work needed to build a result immediately, as a list comprehension does before returning its list.
Eager evaluation calculates every boolean in a list before any begins inspecting that list.
Exhaustion
Exhaustion is an iterator’s state after its stream has ended, when later requests continue to signal that no values remain.
Exhaustion explains why a second list call on the same consumed generator returns an empty list.
Extreme selection
Extreme selection returns an item with the smallest or largest comparison key, keeping the first encountered item when keys tie.
Extreme selection with max(records, key=...) returns a complete record, not just its comparison score.

F

Flattening
Flattening turns nested iterables into a single stream or collection of their members, usually removing one level of nesting.
Flattening several rows with two for clauses keeps their values in row-by-row order.

G

Generator expression
A generator expression is comprehension-style syntax in parentheses that creates an iterator computing its output values on demand.
A generator expression supplies squared values directly to sum without building an intermediate list.
Generator function
A generator function contains yield in its body and returns a generator object when called, delaying execution of that body.
A generator function producing even numbers starts its loop only when the caller requests a value.
Generator object
A generator object is an iterator that runs a generator’s code on request, preserving local state across pauses.
The generator object returned by a function can be partly consumed with next before a loop continues it.
GeneratorExit
GeneratorExit is the exception injected when a paused generator is closed, allowing active cleanup blocks to run.
A generator must not yield another value while responding to GeneratorExit during close().
Groupby
The groupby iterator yields a key and a shared-source iterator for each consecutive run of equal-key values.
Groupby gives separate groups for a label that reappears after a different label.

H

Hashability
Hashability lets a value serve as a dictionary key or set element by providing a consistent hash and equality behavior.
Hashability allows a tuple of strings to identify a location; a mutable list cannot be used that way.

I

In-place sort
An in-place sort rearranges an existing list through .sort() and returns None, instead of returning a new sorted list.
An in-place sort updates the list itself, so assigning its return value would replace the list name with None.
Infinite generator
An infinite generator can keep producing values without normal exhaustion and therefore needs a consumer that supplies a stopping rule.
An infinite generator of Fibonacci numbers can be inspected safely with a finite islice prefix.
Input pool
An input pool is the stored finite sequence of source values used by combinatorial iterators to construct their result tuples.
An input pool must finish loading before product can begin producing its lazy output.
Insertion order
Insertion order is the order in which dictionary keys first enter the mapping; replacing a value does not move its key.
Insertion order keeps a repeated key in its original position after a later value overwrites the first.
Iterable
An iterable is an object accepted by iter(), providing values through the iterator returned for a pass through it.
A list is an iterable that can provide fresh independent iterators for two loops.
Iteration order
Iteration order is the sequence in which an iterable supplies its values, which determines the order of a list comprehension’s output.
A list comprehension preserves iteration order when it converts a sequence of readings.
Iterator
An iterator supplies successive values through next() and returns itself from iter(), retaining the current progress of one pass.
A zip iterator remains at its current position when a second consumer starts reading it.
Iterator protocol
The iterator protocol requires __iter__ to return the iterator and __next__ to supply a value or raise StopIteration.
The iterator protocol lets a custom countdown work with for, sum, and list.
Iterator slice
An iterator slice selects positions through islice, consuming skipped inputs while accepting no negative indexes or nonpositive step.
An iterator slice can take a short preview from an endless count without exhausting the source.
Iterator state
Iterator state is the information recording progress through one pass, such as a current index or the next countdown number.
Iterator state changes before each countdown value is returned, so later requests move forward.

K

Key function
A key function takes one item and returns the comparable value used for sorting or selection, while the result retains the original item.
The key function len orders words by length without replacing the words with numbers.

L

Lambda expression
A lambda expression creates an anonymous function with a single expression body whose value becomes the result of a call.
A lambda expression can extract the final character of each word as its sorting key.
Late binding
Late binding means a function reads a name from an enclosing scope when called, instead of saving its current value at creation.
Late binding makes lambdas created in one loop read the loop’s final value when called later.
Lazy evaluation
Lazy evaluation delays computing a value until a consumer requests it, which can skip work the consumer never needs.
Lazy evaluation postpones a conversion error until the pipeline actually requests the invalid input.
Lazy sequence
A lazy sequence computes values as needed but still supports sequence operations such as indexing and repeated iteration.
The lazy sequence range(10) can be reused even though it does not store all ten integers as a list.
Leftmost iterable
The leftmost iterable is the source after the first in in a generator expression, whose iterator is obtained at creation.
Rebinding the leftmost iterable’s name later does not replace the iterator already captured by the expression.
List comprehension
A list comprehension is an expression that builds a new list by transforming each accepted item from an iterable.
A list comprehension can convert stored distances from kilometers to meters while keeping their order.

M

Mask selection
Mask selection keeps data items according to parallel truthy or falsy selector values, as compress does.
Mask selection with compress keeps only the names whose matching selector is truthy.
Materialization
Materialization consumes values from an iterable and stores them together in a concrete collection such as a list or tuple.
Materialization with list(map(...)) makes the transformed values available for repeated access.
Multi-pass sort
A multi-pass sort applies stable sorts from secondary to primary criterion, preserving earlier ordering inside later ties.
A multi-pass sort handles descending names within ascending age groups by sorting names first.

N

Nested comprehension
A nested comprehension places one comprehension inside another’s result expression, often creating a list of lists.
A nested comprehension builds a separate multiplication row for each outer-loop value.

O

Outer loop
An outer loop supplies values that remain fixed while an inner loop runs; in a multi-clause comprehension it is the first for.
The outer loop selects a row before the inner loop visits its individual values.

P

Pairwise iteration
Pairwise iteration yields overlapping pairs of adjacent inputs, making each neighboring change available for calculation.
Pairwise iteration over temperatures lets each output subtract the previous reading from the next one.
Permutation
A permutation is an ordered selection of input positions without reuse, so rearranging the selected positions gives a different result.
A permutation assigns distinct candidates to two different roles where swapping them changes the assignment.
Pipeline
A pipeline connects stages that consume iterables and produce processed values, with requests driven by the final consumer.
A pipeline can strip lines, remove blanks, and parse numbers before adding them in a final sum.
Prefix selection
Prefix selection keeps only an initial run satisfying a predicate, ending at its first failure as takewhile does.
Prefix selection stops at the first out-of-range reading even if later readings would pass again.
Priming
Priming starts a generator with next() or send(None) so it reaches a yield that can receive a later sent value.
Priming a running-average generator prepares its first suspended yield to accept a number.

R

Rebinding
Rebinding assigns a name to another object, which differs from changing the contents of the object previously named.
Rebinding a source list name does not affect a generator’s existing iterator over the original list.
Reduction
Reduction combines inputs into a single final result, as functools.reduce does without yielding intermediate results.
Reduction gives one final combined value where accumulate would expose the running values.
Resource lifetime
Resource lifetime is the period during which a resource remains open or available, including pauses inside an active generator.
A file’s resource lifetime extends across yields inside its with block until completion or explicit close.
Result expression
A result expression is the expression at the front of a comprehension that supplies an output value for each accepted input.
The result expression name.upper() converts each accepted name into uppercase text.
Retained state
Retained state is the data kept alive across generator pauses, including local variables, source references, and any stored history.
Retained state grows when a generator appends every processed record to a local history list.
Reusable iterable
A reusable iterable can supply a fresh iterator for each pass, allowing repeated or nested loops with separate progress.
A reusable iterable playlist returns a new iterator over its stored songs each time.

S

Send
The send method resumes a generator, supplies the paused yield expression’s value, and returns the next value yielded.
A send of a new measurement can update a running-average generator and return its revised average.
Sequence protocol
The older sequence protocol supports iteration through __getitem__ at indexes starting from zero until IndexError signals the end.
A class using the sequence protocol may work with iter() without an explicit __iter__ method.
Set comprehension
A set comprehension builds a set from one result expression, keeping unique hashable values without a defined iteration order.
A set comprehension can normalize repeated labels before a sorted display is built.
Shared reference
A shared reference occurs when several names or container entries refer to the same object, so a mutation is visible through each one.
A shared reference makes repeated nested rows change together when one cell is assigned.
Short-circuit evaluation
Short-circuit evaluation skips an expression once a condition or logical result makes evaluating it unnecessary.
Short-circuit evaluation of a conditional expression avoids its division branch when the denominator is zero.
Short-circuiting consumer
A short-circuiting consumer stops requesting values as soon as its answer is known, such as any after a truthy value.
A short-circuiting consumer can leave later generator calculations and their possible errors untouched.
Side effect
A side effect is an action that changes state or interacts with the outside world, such as printing, writing, or modifying another object.
Printing is a side effect, so a loop expresses a printing task without building a throwaway list.
Single-pass iteration
Single-pass iteration advances one stream position, so consumed values are unavailable to later consumers of that same iterator.
Single-pass iteration means a preview of two values from an iterator changes where a later sum over that iterator begins.
Snapshot
A snapshot is a separate collection of values used to stabilize an iteration source while the original collection is changed.
A snapshot of dictionary keys allows deletion from the original dictionary during the loop.
Stable sort
A stable sort keeps the original relative order of items whose comparison keys are equal, including when Python sorts descending.
A stable sort preserves arrival order among records with the same score.
Stage
A stage is one processing step in a pipeline, responsible for a focused transformation, selection, or combination of inputs.
A parsing stage can catch invalid numeric strings while passing valid numbers downstream.
Starmap
The starmap iterator unpacks each input tuple into separate positional arguments when it calls the supplied function.
Starmap can pass each base–exponent pair to pow without a custom unpacking function.
Starred unpacking
Starred unpacking assigns unmatched values to a list for a starred target, consuming the remaining iterable to collect them.
Starred unpacking in first, *rest = source gathers every remaining value into rest.
StopIteration
StopIteration is the exception an iterator raises when no values remain, which a for loop handles as normal completion.
A next call with a default handles StopIteration by returning that default when the stream ends.
Strict zip
Strict zip is zip(..., strict=True), which raises ValueError during consumption when the input lengths differ.
Strict zip catches a missing measurement when record names and readings are expected to align.
Suspension
Suspension is the pause at a generator’s yield, during which its local variables and execution position remain available for resumption.
Suspension keeps a running total alive between two requests for a generator’s values.

T

Tee buffer
A tee buffer retains values already read by leading branches until lagging branches have requested those values too.
A tee buffer can become large when one branch consumes a file before another branch starts.
Throw
The throw method resumes a generator by raising a supplied exception at its paused yield, where generator code may handle it.
A throw of ValueError("bad input") makes that exception arise at the generator’s suspended yield.
Top-n selection
Top-n selection returns a ranked list of a requested number of highest or lowest items, using a key when needed.
Top-n selection with heapq.nlargest is useful for a small shortlist from many records.
Transposition
Transposition exchanges a matrix’s rows and columns, collecting the values at each column position into a new row.
Transposition turns a two-row, three-column rectangular matrix into three rows with two values each.
Truthiness
Truthiness is the true-or-false behavior of a value in a condition; zero, None, and empty containers are falsy.
Testing truthiness would drop a valid zero reading, so a missing-value filter should test for None.
Tuple key
A tuple key holds several comparison criteria in order; later components decide a comparison only after earlier components tie.
A tuple key can place higher numeric scores first and use ascending names to resolve ties.
Tuple unpacking
Tuple unpacking assigns the members of an incoming tuple to separate names so an expression can work with each member directly.
Tuple unpacking in for name, count in stock.items() gives the key and value separate names.

U

Unpacking comprehension
An unpacking comprehension expands each produced iterable or mapping into the result using front-position * or **, from Python 3.15.
The unpacking comprehension [*row for row in rows] collects all row elements into one list.

Y

Yield
Yield is the operation that provides a value to a generator’s caller and suspends execution until the next resumption.
A yield inside a countdown loop preserves the current counter while the consumer processes its value.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started