Loops: Advanced
Why data moves in batches
Batch boundaries from a range step
When the data is a list of known length, range(0, total_rows, batch_size) produces each batch's first index. The end is the start plus the batch size. When that would run past the total, the end is pulled back to the total.
Stepping by 4 from 0 gives 3 starts, the last at 8. For the third batch, start + batch_size is 12, past the 10 rows that exist, so the clamp sets end to 10 and the batch holds 2 rows. Without the clamp, code that reads rows up to end - 1 would ask for row 10 and raise an IndexError.
To know the batch count in advance, divide the total by the size and round up. Floor division rounds down, so add batch_size - 1 first: (10 + 4 - 1) // 4 is 13 // 4, which is 3. When the total divides evenly, the added amount falls short of the next multiple, so (12 + 3) // 4 is still exactly 3.
This loop splits 13 rows into batches of 5. Where does the last batch start, and how many rows does it hold?
The accumulator: batches from any iterable
A range step needs the length up front. A generator, a file read line by line, or a stream of events has no length until it ends. The accumulator form handles all of these sources. It appends each item to a batch list, and when the list reaches the batch size, it hands the list off and starts a new empty one. batch.append(event) adds 1 item to the end of the list, and len(batch) counts its items.
events = ["e1", "e2", "e3", "e4", "e5", "e6", "e7"]batch_size = 3batch = []for event in events:batch.append(event)if len(batch) == batch_size:print("send", batch)batch = []if batch:print("send", batch)
When the for loop ends, batch still holds 'e7', which never reached size 3. The if batch: check relies on truthiness: an empty list is falsy, so the final send runs only when items are left over. With 6 events, the second send would empty the list and the check would skip.
Packaging the accumulator as a generator
A generator function packages the accumulator, so every batch loop becomes a single for batch in batches(...) line and the tail is handled in 1 place. def batches(items, size): names a reusable block of code that takes 2 inputs. Each yield batch hands 1 batch to the for loop that asked for it and pauses there. When the loop asks for the next batch, the code resumes on the line after the yield.
The input here is a range, and the generator never asks for its length, so the same code batches anything you can loop over, including a file or another generator. The generator yields lazily, so only 1 batch sits in memory at a time while the job pages through millions of rows.
This loop collects 11 order IDs in batches of 4 and has no flush after it. What does it print?
A window that moves 1 step at a time
A sliding window is a run of k consecutive items that moves along a sequence 1 position per step. A rolling average on a dashboard, an alert on more than 50 errors in any 5 minutes, and the busiest hour of a day all ask the same question of every stretch of a fixed length. Here are 7 minutes of ride requests with k = 3.
| Window | Minutes | Values | Sum |
|---|---|---|---|
| 0 | 0 to 2 | 4, 7, 2 | 13 |
| 1 | 1 to 3 | 7, 2, 9 | 18 |
| 2 | 2 to 4 | 2, 9, 5 | 16 |
| 3 | 3 to 5 | 9, 5, 1 | 15 |
| 4 | 4 to 6 | 5, 1, 8 | 14 |
Re-summing versus sliding
The sliding version keeps 1 running total. Each step adds requests[i] as it enters on the right and subtracts requests[i - k] as it leaves on the left. That is 2 operations per step, whatever the window size. Take a full day of per-minute counts, 1,440 values, with a 60-minute window. Re-summing reads each value roughly 60 times. Sliding reads each value at most twice, as it enters and again as it leaves.
requests = [4, 7, 2, 9, 5, 1, 8]k = 3window_sum = 0for i in range(k):window_sum += requests[i]best = window_sumbest_start = 0for i in range(k, len(requests)):window_sum += requests[i] - requests[i - k]if window_sum > best:best = window_sumbest_start = i - k + 1print("best window starts at minute", best_start)print("total requests:", best)
The first loop builds the opening window once, by adding every item. From i = 3 on, each step is a single line. Adding 9 and subtracting 4 turns 13 into 18, the new best, so best_start records minute 1. The later sums fall from 16 down to 14 and never beat it. The code stores i - k + 1 because i is where a window ends, and a report wants where it starts.
A sliding sum over [5, 2, 8, 1] with k = 2 holds 10 for the window [2, 8]. Which update moves it to the window [8, 1]?
Windows that grow and shrink
Some questions have no fixed width. Finding the longest run of consecutive log messages that fits in a 6 KB packet needs a window whose size is the answer. A variable window keeps 2 indexes. right moves forward 1 item per iteration, and left moves forward only while the window breaks the rule.
sizes_kb = [2, 1, 3, 4, 1, 1, 2, 1, 5]limit = 6left = 0total = 0best_len = 0best_left = 0for right in range(len(sizes_kb)):total += sizes_kb[right]while total > limit:total -= sizes_kb[left]left += 1if right - left + 1 > best_len:best_len = right - left + 1best_left = leftprint("longest run:", best_len, "messages")print("starts at message", best_left)
A while inside a for looks like it could multiply the work, so count the moves instead. left only increases and never passes the end of the list. Over the whole run it advances at most 9 times for 9 messages. The inner loop's total work is therefore capped by the length of the list, the same cap as the outer loop.
- ▸Adding an item can only push the window further from valid, and removing an item only brings it closer.
- ▸Sizes and durations can't go below zero, and neither can counts, so a sum-under-a-limit window qualifies.
- ▸With negative values, dropping an item can raise the total, and the shrink step can throw away the best answer.
When 1 pass is not enough
The pattern comes down to 3 lines. changed starts as True so the first pass runs. It resets to False at the top of each pass, so a pass reports only its own work. Every line that edits the data sets it back to True. The loop exits after the first pass in which no fix fired, so the final pass edits nothing and only confirms. Below, merged_into[target] reads the value stored under a key, and assigning to merged_into[account] replaces it.
merged_into = {"a": "b", "b": "c", "c": "d", "d": "d", "e": "e"}passes = 0changed = Truewhile changed:changed = Falsepasses += 1for account, target in merged_into.items():final = merged_into[target]if final != target:merged_into[account] = finalchanged = Trueprint("after pass", passes, merged_into)print("passes:", passes)
| After | a | b | c | d | e | Changed |
|---|---|---|---|---|---|---|
| start | b | c | d | d | e | |
| pass 1 | c | d | d | d | e | yes |
| pass 2 | d | d | d | d | e | yes |
| pass 3 | d | d | d | d | e | no |
b gets its final answer in pass 1, because its target c pointed at d from the start. The same pass moves a to c, which is closer but not final, and pass 2 finishes a. Pass 3 finds nothing to fix, and that empty pass ends the loop. Assigning to merged_into[account] during .items() is safe because it replaces a value and leaves the keys alone. The next section covers what happens when the keys change.
The pass count depends on the order of the keys. With d listed first and a last, pass 1 resolves the whole chain, because each account reads a target that was fixed earlier in the same pass. Pass 2 then confirms. The loop is correct in either order, which is its value: nobody has to work out the right order.
Putting a ceiling on the passes
The capped loop above runs on the same 5 accounts with max_passes = 2. What does it print?
changed = True on the line next to every edit. A branch that edits the data without setting the flag lets the loop exit while some records are still half settled.Why removing during a for loop skips items
A for loop over a list keeps a hidden position. It reads index 0, then 1, then 2, until the position passes the end. readings.remove(value) deletes the first item equal to value and shifts every later item 1 place left. The hidden position does not shift with them, so the item that slides into the current slot is never visited.
readings = [12, -1, -1, 7, -1, 9]for value in readings:print("checking", value)if value == -1:readings.remove(value)print(readings)
| Position | Value read | Action | List afterwards |
|---|---|---|---|
| 0 | 12 | keep | [12, -1, -1, 7, -1, 9] |
| 1 | -1 | remove | [12, -1, 7, -1, 9] |
| 2 | 7 | keep | [12, -1, 7, -1, 9] |
| 3 | -1 | remove | [12, 7, -1, 9] |
| 4 | none | loop ends | [12, 7, -1, 9] |
3 safe ways to remove items
Build a new list
Loop over a copy
list(readings) builds a second list holding the same items. Loop over the copy and remove from the original. The copy never shifts, so every value is visited.
Walk backwards by index
del nums[i] deletes the item at index i and shifts only the items after it. A backward loop has already visited those items, so every index still ahead of it stays valid.
# Reverse iteration for safe deletionnums = [1, 2, 3, 4, 5, 6, 7, 8]for i in range(len(nums) - 1, -1, -1):if nums[i] % 2 == 0:del nums[i]print("After removing evens:", nums)
range(len(nums) - 1, -1, -1) counts down from 7 to 0, since the stop of -1 is excluded. The program prints After removing evens: [1, 3, 5, 7].
Dicts refuse to change size
A dict checks its own size on every step of a loop over it. Deleting or adding a key mid-loop raises a RuntimeError at the next step. Replacing the value of an existing key is allowed, which is why the merge loop in the previous section worked. del retries[job] removes a key and its value.
The delete went through before the error, so the dict is changed and the loop stopped partway. That is a bad combination for a job that resumes. The fix is the copy again: for job, count in list(retries.items()): freezes the pairs into a list first, and the loop can then delete from the dict freely.
Appending is the one change that a for loop over a list keeps up with, because the hidden position reaches the new items. That makes for n in nums: nums.append(n) run until memory runs out. It also makes a work list possible on purpose. Processing an item appends the follow-up work it reveals, and the loop ends once nothing new is added.
What happens when this runs?
One question about a whole sequence
any(iterable) returns True if at least 1 item is truthy, and all(iterable) returns True if every item is. Pass either one a generator expression, the parenthesised form of a generator. A loop with a flag then becomes 1 line that reads like the question: is any latency over 100 ms, is every count present? When the generator expression is the only argument, its own parentheses can go.
They stop at the first deciding item
any() stops at the first truthy item, since 1 is enough, and all() stops at the first falsy item. The generator below prints each value as it is checked, so the output shows where each call stopped.
Empty input and other traps
any([]) is False, since no item is truthy, and all([]) is True, since no item fails. That second rule is sound logic and a real hazard. A quality gate written as all(row > 0 for row in batch) passes an empty batch, so an upstream outage that delivers 0 rows looks clean. Test for emptiness first with short-circuit and: if batch and all(row > 0 for row in batch):.
Passing raw values tests their truthiness, and 0 is falsy. all(row_counts) is False because 1 table loaded 0 rows, even when the question was whether every count arrived. Write the condition you mean inside the generator expression, here count is not None. Pass raw values only when truthiness is the test.
- ▸Always
TrueorFalse, never an item from the input.orandanddiffer here because they return an operand. - ▸
any()of an empty sequence isFalse, andall()of an empty sequence isTrue. - ▸A generator passed in is consumed up to the item where the call stopped, and later calls see only the rest.
Both calls share 1 generator. What does this print?
Capstone: a batch quality gate
not all(total >= 0 for total in batch) and any(total < 0 for total in batch) mean the same thing, by De Morgan's laws from the control flow track. Choose the one that matches how the rule is written down.
> Picture the nightly job at Uber that prepares a city's trip data for the pricing team. It reads the day's trip events, drops cancelled rides, resolves rider accounts that were merged into other accounts, finds each city's busiest 60-minute window, and loads the results to a service that takes 500 rows per call.
Batches, sliding windows, loops that settle, safe mid-loop edits, and any()/all() across whole sequences.
- Category
- Python
- Difficulty
- advanced
- Duration
- 34 minutes
- Challenges
- 17 hands-on challenges
Topics covered: Iterating in Fixed-Size Chunks, Sliding Window Pattern, Looping Until Nothing Changes, Modifying While Looping, Using any() and all()
Lesson Sections
- Iterating in Fixed-Size Chunks (concepts: Two-Pointer)
Why data moves in batches Most systems that receive data cap how much they accept per call: a bulk insert takes a limited number of rows per statement, and an HTTP API takes a limited number of records per request. One row per call pays a network round trip for every row, and everything in 1 call gets rejected. A batch loop hands the data over in groups of a fixed size. It also has to decide what happens to the rows left over when the total does not divide evenly. Batch boundaries from a range s
- Sliding Window Pattern (concepts: Sliding Window)
A window that moves 1 step at a time Compare 2 neighbouring rows. Window 1 drops 4 and picks up 9, but it keeps the 7 and 2 from window 0. Each step shares k - 1 items with the step before it. Summing every window from scratch adds those shared items again each time. Re-summing versus sliding Windows that grow and shrink At message 3, a 4 KB message pushes the total to 10, so the inner while drops messages 0 through 2 until the total is back to 4. Messages 4 and 5 join message 3 for 6 KB, exactl
- Looping Until Nothing Changes (concepts: Iteration)
When 1 pass is not enough Some data only settles after several passes, and the number of passes depends on the data. Customer accounts get merged into other accounts, and those accounts get merged again: a into b, b into c, c into d. Replacing each account's target with its target's target shortens every chain. A long chain needs that step repeated. The loop for this job keeps making full passes until a pass changes nothing. Putting a ceiling on the passes A rule that undoes another rule, or dat
- Modifying While Looping (concepts: List Modification)
Why removing during a for loop skips items The loop goes wrong in 2 ways. The skip hides the -1 that slid into position 1. The second remove then deletes the first -1 in the list, at index 1, which is a different -1 from the one the loop was reading at index 3. The loop never reads 9 at all. Nothing raises an error, so the job finishes and loads a -1 sentinel into the clean table. 3 safe ways to remove items Build a new list The clearest fix leaves the list being read untouched and appends each
- Using any() and all() (concepts: Boolean Operators)
One question about a whole sequence They stop at the first deciding item Out of 4 values, any() needed 2 checks and all() needed 1. Stopping early pays off when each check is slow, such as opening a file or calling a service. It also pays off when the iterable is a generator over millions of rows, because the rows after the deciding one are never produced. Empty input and other traps Capstone: a batch quality gate The last example combines a batch generator with both checks. Order totals arrive