script_15.py - List Partitioning
Code
See script_15.py for full code.
Explanation
Line 8: def chunk_list(lst, chunk_size):
- Function takes list and desired chunk size
- Returns list of lists (chunks)
Line 10: return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
- List comprehension creating chunks
- range(0, len(lst), chunk_size) generates starting indices
- Step of chunk_size: 0, 5, 10, 15, 20 (if chunk_size=5)
- lst[i:i + chunk_size] slices chunk from list
- Last chunk may be smaller (slice handles out-of-bounds)
Line 14: data = list(range(1, 26))
- Creates list [1, 2, 3, ..., 25]
Line 22: from itertools import islice
- islice() for memory-efficient slicing
Line 24: def chunk_iterable(iterable, size):
- Works with any iterable (not just lists)
- Generator function (uses yield)
Line 26: iterator = iter(iterable)
- iter() creates iterator from iterable
- Iterator can be consumed (one-way traversal)
Line 27-30: while True: infinite loop
- Continues until explicitly broken
Line 28: chunk = list(islice(iterator, size))
- islice(iterator, size) gets next size elements
- Advances iterator position
- Returns iterator, converted to list
- Consumes elements from iterator
Line 29: if not chunk:
- Empty list is falsy
- Detects end of iteration
Line 30: break
- Exits infinite loop
Line 31: yield chunk
- yield makes function a generator
- Returns chunk but remembers position
- Function can be resumed
Line 46: BATCH_SIZE = 20
- Constant for API rate limiting
Line 57: evens = [n for n in numbers if n % 2 == 0]
- List comprehension for filtering
- Creates new list with even numbers
Line 64: def partition_by(lst, predicate):
- Takes list and function (predicate)
Line 65-66: Two empty lists
- true_list for elements where predicate returns True
- false_list for False
Line 67: for item in lst:
- Single pass through list
Line 68: if predicate(item):
- Calls predicate function on item
- predicate is function parameter
Line 69-72: Append to appropriate list - Partitions in one pass - More efficient than two comprehensions