Additional building blocks, recipes, and routines for working with Python iterables beyond itertools.
—
Functions for extracting, filtering, and selecting elements from iterables.
Extract specific items or ranges from iterables.
def take(n, iterable):
"""
Return first n items as a list.
Args:
n: Number of items to take
iterable: Input iterable
Returns:
List of first n items (or all items if fewer than n)
"""
def tail(n, iterable):
"""
Return last n items as an iterator.
Args:
n: Number of items to take from end
iterable: Input iterable
Returns:
Iterator of last n items
"""
def first(iterable, default=None):
"""
Return first item of iterable.
Args:
iterable: Input iterable
default: Value to return if iterable is empty
Returns:
First item or default if empty
Raises:
ValueError: If iterable is empty and no default provided
"""
def last(iterable, default=None):
"""
Return last item of iterable.
Args:
iterable: Input iterable
default: Value to return if iterable is empty
Returns:
Last item or default if empty
Raises:
ValueError: If iterable is empty and no default provided
"""
def nth(iterable, n, default=None):
"""
Return nth item (0-indexed) from iterable.
Args:
iterable: Input iterable
n: Index of item to retrieve
default: Value to return if index out of range
Returns:
Item at index n or default if out of range
"""Usage Examples:
from more_itertools import take, first, last, nth
# Take first n items
data = range(100)
first_10 = take(10, data)
# Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Safe first/last access
print(first([1, 2, 3])) # 1
print(first([], 'empty')) # 'empty'
print(last([1, 2, 3])) # 3
# Nth item access
print(nth([10, 20, 30], 1)) # 20
print(nth([10, 20], 5, 'missing')) # 'missing'Select items based on conditions and predicates.
def one(iterable, too_short=None, too_long=None):
"""
Return single item from iterable, ensuring exactly one exists.
Args:
iterable: Input iterable
too_short: Exception to raise if iterable is empty
too_long: Exception to raise if iterable has multiple items
Returns:
Single item from iterable
Raises:
ValueError: If iterable doesn't contain exactly one item
"""
def only(iterable, default=None, too_long=None):
"""
Return only item from iterable or default if empty.
Args:
iterable: Input iterable
default: Value to return if iterable is empty
too_long: Exception to raise if iterable has multiple items
Returns:
Single item or default if empty
Raises:
ValueError: If iterable has more than one item
"""
def nth_or_last(iterable, n):
"""
Return nth item or last item if n is beyond end.
Args:
iterable: Input iterable
n: Index to retrieve
Returns:
Item at index n or last item if n too large
"""
def first_true(iterable, default=None, pred=None):
"""
Return first true value or first value passing predicate.
Args:
iterable: Input iterable
default: Value to return if no true value found
pred: Optional predicate function
Returns:
First true value or default
"""Extract items based on predicates and conditions.
def extract(pred, iterable):
"""
Extract items matching predicate from iterable.
Args:
pred: Predicate function
iterable: Input iterable
Returns:
Tuple of (extracted_items, remaining_items) iterators
"""
def filter_except(function, iterable, *exceptions):
"""
Filter items, handling specified exceptions.
Args:
function: Filter function
iterable: Input iterable
*exceptions: Exception types to catch and skip
Returns:
Iterator of items that pass filter without exceptions
"""
def map_except(function, iterable, *exceptions):
"""
Map function over iterable, handling specified exceptions.
Args:
function: Mapping function
iterable: Input iterable
*exceptions: Exception types to catch and skip
Returns:
Iterator of mapped values, skipping exceptions
"""
def filter_map(function, iterable):
"""
Apply function and filter out falsy results.
Args:
function: Function to apply
iterable: Input iterable
Returns:
Iterator of truthy function results
"""
def map_if(iterable, pred, func, func_else=lambda x: x):
"""
Conditionally apply function based on predicate.
Args:
iterable: Input iterable
pred: Predicate function
func: Function to apply if predicate true
func_else: Function to apply if predicate false
Returns:
Iterator of conditionally mapped values
"""Find positions and locate items in iterables.
def locate(iterable, pred=bool, window_size=None):
"""
Find positions where predicate is true.
Args:
iterable: Input iterable
pred: Predicate function (default: bool)
window_size: Size of sliding window for predicate
Returns:
Iterator of indices where predicate is true
"""
def rlocate(iterable, pred=bool, window_size=None):
"""
Find positions where predicate is true, from right to left.
Args:
iterable: Input iterable
pred: Predicate function (default: bool)
window_size: Size of sliding window for predicate
Returns:
Iterator of indices where predicate is true (reverse order)
"""Select based on exact counts and quantities.
def exactly_n(iterable, n, predicate=bool):
"""
Check if exactly n items match predicate.
Args:
iterable: Input iterable
n: Expected count
predicate: Predicate function
Returns:
True if exactly n items match predicate
"""
def strictly_n(iterable, n, too_short=None, too_long=None):
"""
Ensure iterable has exactly n items.
Args:
iterable: Input iterable
n: Expected number of items
too_short: Exception if fewer than n items
too_long: Exception if more than n items
Returns:
List of exactly n items
Raises:
ValueError: If item count doesn't match n
"""Usage Examples:
from more_itertools import extract, locate, exactly_n
# Extract items by predicate
is_even = lambda x: x % 2 == 0
evens, odds = extract(is_even, [1, 2, 3, 4, 5, 6])
print(list(evens)) # [2, 4, 6]
print(list(odds)) # [1, 3, 5]
# Find positions
positions = list(locate([0, 1, 0, 1, 0], lambda x: x == 1))
print(positions) # [1, 3]
# Count verification
print(exactly_n([1, 2, 3, 4], 2, lambda x: x % 2 == 0)) # True
print(exactly_n([1, 2, 3, 4], 3, lambda x: x % 2 == 0)) # FalseInstall with Tessl CLI
npx tessl i tessl/pypi-more-itertools