0
# Selecting and Filtering
1
2
Functions for extracting, filtering, and selecting elements from iterables.
3
4
## Capabilities
5
6
### Basic Selection
7
8
Extract specific items or ranges from iterables.
9
10
```python { .api }
11
def take(n, iterable):
12
"""
13
Return first n items as a list.
14
15
Args:
16
n: Number of items to take
17
iterable: Input iterable
18
19
Returns:
20
List of first n items (or all items if fewer than n)
21
"""
22
23
def tail(n, iterable):
24
"""
25
Return last n items as an iterator.
26
27
Args:
28
n: Number of items to take from end
29
iterable: Input iterable
30
31
Returns:
32
Iterator of last n items
33
"""
34
35
def first(iterable, default=None):
36
"""
37
Return first item of iterable.
38
39
Args:
40
iterable: Input iterable
41
default: Value to return if iterable is empty
42
43
Returns:
44
First item or default if empty
45
46
Raises:
47
ValueError: If iterable is empty and no default provided
48
"""
49
50
def last(iterable, default=None):
51
"""
52
Return last item of iterable.
53
54
Args:
55
iterable: Input iterable
56
default: Value to return if iterable is empty
57
58
Returns:
59
Last item or default if empty
60
61
Raises:
62
ValueError: If iterable is empty and no default provided
63
"""
64
65
def nth(iterable, n, default=None):
66
"""
67
Return nth item (0-indexed) from iterable.
68
69
Args:
70
iterable: Input iterable
71
n: Index of item to retrieve
72
default: Value to return if index out of range
73
74
Returns:
75
Item at index n or default if out of range
76
"""
77
```
78
79
**Usage Examples:**
80
81
```python
82
from more_itertools import take, first, last, nth
83
84
# Take first n items
85
data = range(100)
86
first_10 = take(10, data)
87
# Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
88
89
# Safe first/last access
90
print(first([1, 2, 3])) # 1
91
print(first([], 'empty')) # 'empty'
92
print(last([1, 2, 3])) # 3
93
94
# Nth item access
95
print(nth([10, 20, 30], 1)) # 20
96
print(nth([10, 20], 5, 'missing')) # 'missing'
97
```
98
99
### Conditional Selection
100
101
Select items based on conditions and predicates.
102
103
```python { .api }
104
def one(iterable, too_short=None, too_long=None):
105
"""
106
Return single item from iterable, ensuring exactly one exists.
107
108
Args:
109
iterable: Input iterable
110
too_short: Exception to raise if iterable is empty
111
too_long: Exception to raise if iterable has multiple items
112
113
Returns:
114
Single item from iterable
115
116
Raises:
117
ValueError: If iterable doesn't contain exactly one item
118
"""
119
120
def only(iterable, default=None, too_long=None):
121
"""
122
Return only item from iterable or default if empty.
123
124
Args:
125
iterable: Input iterable
126
default: Value to return if iterable is empty
127
too_long: Exception to raise if iterable has multiple items
128
129
Returns:
130
Single item or default if empty
131
132
Raises:
133
ValueError: If iterable has more than one item
134
"""
135
136
def nth_or_last(iterable, n):
137
"""
138
Return nth item or last item if n is beyond end.
139
140
Args:
141
iterable: Input iterable
142
n: Index to retrieve
143
144
Returns:
145
Item at index n or last item if n too large
146
"""
147
148
def first_true(iterable, default=None, pred=None):
149
"""
150
Return first true value or first value passing predicate.
151
152
Args:
153
iterable: Input iterable
154
default: Value to return if no true value found
155
pred: Optional predicate function
156
157
Returns:
158
First true value or default
159
"""
160
```
161
162
### Extraction and Filtering
163
164
Extract items based on predicates and conditions.
165
166
```python { .api }
167
def extract(pred, iterable):
168
"""
169
Extract items matching predicate from iterable.
170
171
Args:
172
pred: Predicate function
173
iterable: Input iterable
174
175
Returns:
176
Tuple of (extracted_items, remaining_items) iterators
177
"""
178
179
def filter_except(function, iterable, *exceptions):
180
"""
181
Filter items, handling specified exceptions.
182
183
Args:
184
function: Filter function
185
iterable: Input iterable
186
*exceptions: Exception types to catch and skip
187
188
Returns:
189
Iterator of items that pass filter without exceptions
190
"""
191
192
def map_except(function, iterable, *exceptions):
193
"""
194
Map function over iterable, handling specified exceptions.
195
196
Args:
197
function: Mapping function
198
iterable: Input iterable
199
*exceptions: Exception types to catch and skip
200
201
Returns:
202
Iterator of mapped values, skipping exceptions
203
"""
204
205
def filter_map(function, iterable):
206
"""
207
Apply function and filter out falsy results.
208
209
Args:
210
function: Function to apply
211
iterable: Input iterable
212
213
Returns:
214
Iterator of truthy function results
215
"""
216
217
def map_if(iterable, pred, func, func_else=lambda x: x):
218
"""
219
Conditionally apply function based on predicate.
220
221
Args:
222
iterable: Input iterable
223
pred: Predicate function
224
func: Function to apply if predicate true
225
func_else: Function to apply if predicate false
226
227
Returns:
228
Iterator of conditionally mapped values
229
"""
230
```
231
232
### Positional Operations
233
234
Find positions and locate items in iterables.
235
236
```python { .api }
237
def locate(iterable, pred=bool, window_size=None):
238
"""
239
Find positions where predicate is true.
240
241
Args:
242
iterable: Input iterable
243
pred: Predicate function (default: bool)
244
window_size: Size of sliding window for predicate
245
246
Returns:
247
Iterator of indices where predicate is true
248
"""
249
250
def rlocate(iterable, pred=bool, window_size=None):
251
"""
252
Find positions where predicate is true, from right to left.
253
254
Args:
255
iterable: Input iterable
256
pred: Predicate function (default: bool)
257
window_size: Size of sliding window for predicate
258
259
Returns:
260
Iterator of indices where predicate is true (reverse order)
261
"""
262
```
263
264
### Count-based Selection
265
266
Select based on exact counts and quantities.
267
268
```python { .api }
269
def exactly_n(iterable, n, predicate=bool):
270
"""
271
Check if exactly n items match predicate.
272
273
Args:
274
iterable: Input iterable
275
n: Expected count
276
predicate: Predicate function
277
278
Returns:
279
True if exactly n items match predicate
280
"""
281
282
def strictly_n(iterable, n, too_short=None, too_long=None):
283
"""
284
Ensure iterable has exactly n items.
285
286
Args:
287
iterable: Input iterable
288
n: Expected number of items
289
too_short: Exception if fewer than n items
290
too_long: Exception if more than n items
291
292
Returns:
293
List of exactly n items
294
295
Raises:
296
ValueError: If item count doesn't match n
297
"""
298
```
299
300
**Usage Examples:**
301
302
```python
303
from more_itertools import extract, locate, exactly_n
304
305
# Extract items by predicate
306
is_even = lambda x: x % 2 == 0
307
evens, odds = extract(is_even, [1, 2, 3, 4, 5, 6])
308
print(list(evens)) # [2, 4, 6]
309
print(list(odds)) # [1, 3, 5]
310
311
# Find positions
312
positions = list(locate([0, 1, 0, 1, 0], lambda x: x == 1))
313
print(positions) # [1, 3]
314
315
# Count verification
316
print(exactly_n([1, 2, 3, 4], 2, lambda x: x % 2 == 0)) # True
317
print(exactly_n([1, 2, 3, 4], 3, lambda x: x % 2 == 0)) # False
318
```