0
# Iteration Utilities
1
2
Core iteration utilities and helpers for advanced iteration patterns.
3
4
## Capabilities
5
6
### Functional Iteration
7
8
Functions for functional-style iteration patterns.
9
10
```python { .api }
11
def iterate(func: Callable[[Any], Any], value: Any) -> Iterator[Any]: ...
12
def tabulate(func: Callable[[int], Any], start: int = 0) -> Iterator[Any]: ...
13
def repeatfunc(func: Callable[..., Any], times: int = None, *args: Any) -> Iterator[Any]: ...
14
```
15
16
**Usage:**
17
18
```python
19
from more_itertools import iterate, tabulate, repeatfunc
20
import random
21
22
# Generate sequence by repeatedly applying function
23
fibonacci_like = iterate(lambda x: x[-1] + x[-2], [0, 1])
24
# Generates: [0, 1], [1, 1], [1, 2], [2, 3], [3, 5], [5, 8], ...
25
26
# Tabulate function results
27
squares = tabulate(lambda x: x**2, 0)
28
first_squares = [next(squares) for _ in range(5)] # [0, 1, 4, 9, 16]
29
30
# Repeat function calls
31
random_numbers = repeatfunc(random.random, 5)
32
rand_list = list(random_numbers) # 5 random numbers
33
```
34
35
### Exception Handling Iteration
36
37
Functions for iterating with exception handling.
38
39
```python { .api }
40
def iter_except(func: Callable[[], Any], exception: type | tuple[type, ...], first: Callable[[], Any] = None) -> Iterator[Any]: ...
41
def iter_suppress(iterable: Iterable[Any], *exceptions: type) -> Iterator[Any]: ...
42
```
43
44
**Usage:**
45
46
```python
47
from more_itertools import iter_except, iter_suppress
48
49
# Iterate until exception (useful for reading files/queues)
50
from collections import deque
51
d = deque([1, 2, 3])
52
53
# Read until deque is empty (raises IndexError when empty)
54
values = list(iter_except(d.popleft, IndexError)) # [1, 2, 3]
55
56
# Suppress specific exceptions during iteration
57
def risky_func(x):
58
if x == 2:
59
raise ValueError("Skip this")
60
return x * 2
61
62
data = [1, 2, 3, 4]
63
safe_iter = iter_suppress((risky_func(x) for x in data), ValueError)
64
result = list(safe_iter) # [2, 6, 8] (skips the error case)
65
```
66
67
### Loop Control
68
69
Functions for controlling loop behavior.
70
71
```python { .api }
72
def loops(n: int) -> Iterator[int]: ...
73
```
74
75
**Usage:**
76
77
```python
78
from more_itertools import loops
79
80
# Generate exactly n iterations (0 to n-1)
81
for i in loops(5):
82
print(i) # Prints: 0, 1, 2, 3, 4
83
```
84
85
### Callback and Context Iteration
86
87
Functions for iteration with callbacks and context management.
88
89
```python { .api }
90
def callback_iter(func: Callable[[], Any], callback_func: Callable[[Any], Any], ignore: type | tuple[type, ...] = ()) -> Iterator[Any]: ...
91
def with_iter(context_manager: Any) -> Iterator[Any]: ...
92
```
93
94
**Usage:**
95
96
```python
97
from more_itertools import callback_iter, with_iter
98
99
# Iterate with callback function
100
def data_source():
101
# Simulate data source that eventually exhausts
102
import random
103
if random.random() < 0.3:
104
raise StopIteration
105
return random.randint(1, 100)
106
107
def log_value(value):
108
print(f"Got value: {value}")
109
110
# Read data and log each value
111
values = callback_iter(data_source, log_value, StopIteration)
112
result = list(values)
113
114
# Context manager iteration
115
import tempfile
116
117
# Iterate over context manager
118
with_temp = with_iter(tempfile.NamedTemporaryFile(mode='w'))
119
for temp_file in with_temp:
120
temp_file.write("Hello, world!")
121
break # Usually you'd have some condition to break
122
```