Python Master Course V2 — 029. Efficient Iteration Techniques
SMARTYFY ACADEMY · MODULE 03 · LESSON 029 OF 200
Efficient Iteration Techniques
Study: 75–100 minutes · Prerequisite: Lesson 028 — Loop Patterns and Accumulators
Write iteration that is readable, memory-conscious and appropriate for the data size.
Video lesson
Video not yet available. A verified lesson video link/player can be added here later.
Learning outcomes
- Use enumerate, zip and iterators without unnecessary indexing.
- Distinguish eager lists from lazy generators.
- Apply any, all and generator expressions.
- Understand time complexity and memory tradeoffs.
- Build and test a streaming transaction analyzer.
Iteration as a design choice
Iteration is not only about repeating statements. A professional developer chooses the traversal pattern that communicates intent and avoids unnecessary copies. Iterating directly over items is usually clearer than looping over numeric indexes. Use enumerate() when positions are needed and zip() when two aligned iterables must be processed together. Remember that zip stops when the shortest iterable is exhausted unless strict checking is requested.
Generator expressions produce values on demand rather than allocating a complete intermediate list. This is valuable for large datasets, but generators are consumed during iteration and cannot simply be reused after exhaustion. Prefer clear linear-time passes to repeated scanning of the same collection. Complexity estimates describe growth trends rather than exact wall-clock timing.
Progressive runnable examples
Requirements: Python 3.10 or later. Save each example separately and run with python lesson029.py. Outputs shown are expected results.
1. Enumerate
for index, item in enumerate(["pen", "book", "bag"], start=1):
print(index, item)
1 pen 2 book 3 bag
2. Zip with strict validation
names = ["Ana", "Ravi"]
scores = [85, 92]
for name, score in zip(names, scores, strict=True):
print(f"{name}: {score}")
Ana: 85 Ravi: 92
3. Generator expression
values = [2, 3, 4, 5]
print(sum(x * x for x in values if x % 2 == 0))
20
4. Any and all
scores = [70, 82, 91]
print(all(s >= 60 for s in scores))
print(any(s >= 90 for s in scores))
True True
5. Lazy generator
def squares(limit):
for value in range(limit):
yield value * value
print(list(squares(4)))
[0, 1, 4, 9]
6. Iterator exhaustion
numbers = iter([1, 2, 3])
print(sum(numbers))
print(sum(numbers))
6 0
Understand iterator state
A reusable source and a moving iterator
A list supplies a fresh iterator for each loop. A particular iterator remembers how far it has advanced. Generators produce values on demand; consuming them does not rewind or cache them. Create a new generator for a repeated calculation, or store results when reuse justifies the memory cost.
squares = (value * value for value in [2, 3, 4])
print(next(squares))
print(sum(squares))
print(sum(squares))
Expected output:
4
25
0
Next consumes 4; the first sum consumes 9 and 16; the last sum sees no values.
Strict pairing checks during consumption
Ordinary zip stops when either side ends. strict=True raises ValueError when unequal exhaustion is discovered. Creating a zip object does not validate lengths. Earlier iterations can already have run, and strict zip cannot undo their side effects.
Empty inputs and short-circuit checks
print(any([]))
print(all([]))
values = iter([0, 5, 8])
print(any(values))
print(list(values))
Expected output:
False
True
True
[8]
Any needs one truthy value and stops at 5 here. All requires no falsey values, so an empty input passes all. A required nonempty batch needs a separate check.
The analyzer makes one pass and adds/counts each accepted record exactly once. Its totals and counts have fixed keys, but stored flagged indexes grow with the number of flags. Laziness alone does not make all results constant-memory.
Extra real-world project — Streaming Transaction Analyzer
A reconciliation team needs to analyze a sequence of transaction records without building multiple intermediate lists. Accept dictionary records whose type is R or P and whose amount is nonnegative finite decimal text or a Decimal. Skip malformed records, reject invalid thresholds, and flag original one-based positions only when the amount is strictly greater than the threshold. Decimal avoids binary-float conversion here but still has configurable arithmetic precision. This project uses small classroom datasets. Silent assertions after the sample test empty input, malformed records, boundaries, generator consumption, and invalid thresholds. An assertion failure identifies a regression.
from decimal import Decimal, InvalidOperation
def analyze(records, threshold=Decimal("1000")):
"""Summarize small classroom records; skip malformed records."""
if (not isinstance(threshold, Decimal)
or not threshold.is_finite() or threshold < 0):
raise ValueError("threshold must be a finite nonnegative Decimal")
totals = {"R": Decimal("0"), "P": Decimal("0")}
counts = {"R": 0, "P": 0}
flagged = []
for index, record in enumerate(records, start=1):
if not isinstance(record, dict):
continue
kind = record.get("type")
if kind not in ("R", "P"):
continue
raw_amount = record.get("amount")
if not isinstance(raw_amount, (str, Decimal)):
continue
try:
amount = Decimal(raw_amount)
except InvalidOperation:
continue
if not amount.is_finite() or amount < 0:
continue
totals[kind] += amount
counts[kind] += 1
if amount > threshold:
flagged.append(index)
return totals, counts, flagged
records = [
{"type": "R", "amount": "500.00"},
{"type": "P", "amount": "1250.00"},
{"type": "R", "amount": "200.00"},
{"type": "X", "amount": "10.00"},
]
totals, counts, flagged = analyze(records)
print(totals)
print(counts)
print(flagged)
# Boundary checks are silent when all assertions pass.
assert totals == {"R": Decimal("700.00"), "P": Decimal("1250.00")}
assert counts == {"R": 2, "P": 1} and flagged == [2]
empty = ({"R": Decimal("0"), "P": Decimal("0")}, {"R": 0, "P": 0}, [])
assert analyze(iter([])) == empty
bad_records = [None, {"type": "X", "amount": "9"}, {"type": "R"},
{"type": "R", "amount": "bad"}, {"type": "R", "amount": "-1"},
{"type": "R", "amount": "NaN"}, {"type": "P", "amount": "Infinity"},
{"type": "R", "amount": 1.5}]
assert analyze(bad_records) == empty
stream = (record for record in [{"type": "R", "amount": "1000"},
{"type": "P", "amount": Decimal("1000.01")}])
assert analyze(stream) == ({"R": Decimal("1000"), "P": Decimal("1000.01")},
{"R": 1, "P": 1}, [2])
assert list(stream) == []
for invalid_threshold in [Decimal("-1"), 1000, Decimal("NaN"), Decimal("Infinity")]:
try:
analyze([], invalid_threshold)
except ValueError:
pass
else:
raise AssertionError("Invalid threshold was accepted")
Expected output:
{'R': Decimal('700.00'), 'P': Decimal('1250.00')}
{'R': 2, 'P': 1}
[2]
Testing: Try an empty list, invalid amount, negative amount, exactly 1000, and an input generator. Note that this single pass uses constant-sized totals and counts but stores flagged indexes proportional to the number of flags. For truly bounded memory, stream flags to a consumer instead of accumulating them.
Common mistakes and professional practices
- Using indexes when direct iteration is clearer.
- Silently losing unmatched values with zip; use strict=True when appropriate.
- Reusing a consumed generator.
- Assuming generators always make the entire algorithm constant-memory.
- Comparing performance without considering readability, input size and profiling.
Think, trace, and solve
Attempt each question before revealing its answer.
1. Account for partial consumption
numbers = (n * 2 for n in [1, 2, 3])
print(next(numbers))
print(list(numbers))
print(list(numbers))
Predict the three outputs.
Optional hint
Trace which values remain after each consumer.
Reveal answer and reasoning
Expected output:
2
[4, 6]
[]
Each consumer advances the same iterator. The final list finds nothing left.
2. Locate strict-zip failure
for name, score in zip(["Ana", "Ravi"], [85], strict=True):
print(name, score)
Is anything printed before the error? Name the error class.
Optional hint
Validation happens when the next pair is requested.
Reveal answer and reasoning
Ana 85 prints first. ValueError occurs when the next pair is requested and the shorter iterable has ended. Earlier processing is not rolled back.
3. Require a nonempty batch
What does all(score >= 60 for score in scores) return for empty scores? For a list, also require at least one value.
Optional hint
A required nonempty list needs a separate condition.
Reveal answer and reasoning
scores = []
passed = bool(scores) and all(score >= 60 for score in scores)
print(passed)
Expected output:
False
All of empty input is True; bool(scores) requires a nonempty list. A generator’s truth value does not reveal whether it has values.
4. Trace rejected records and indexes
Use analyze with the default threshold on X/9, R/1000, P/1000.01, and R/NaN records, in that order. Give counts and flags.
Optional hint
A skipped record still occupied a position in the source.
Reveal answer and reasoning
Expected output:
{'R': 1, 'P': 1}
[3]
Unknown type and nonfinite amount are skipped. Exactly 1000 is accepted without a flag. The payment retains original stream position 3.
5. Choose a memory strategy
A million records are read lazily and all are flagged. Is the analyzer constant-memory? How could it avoid storing a million positions?
Optional hint
Inspect which outputs are accumulated.
Reveal answer and reasoning
No: the flagged list grows to a million indexes. Send flags to a consumer as they are found, or keep only a count when individual positions are not required. Preserve the actual reporting requirement.
Mastery checkpoint
Explain enumerate, zip, lazy evaluation and iterator exhaustion; run the project; and create tests for an empty batch and malformed data. Next: Lesson 030 — Loops Project and Review.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.