Additional building blocks, recipes, and routines for working with Python iterables beyond itertools.
—
Functions that compute summaries and statistics over iterables.
Functions for measuring iterables and counting elements.
def ilen(iterable: Iterable[Any]) -> int: ...
def quantify(iterable: Iterable[Any], pred: Callable[[Any], bool] = bool) -> int: ...Usage:
from more_itertools import ilen, quantify
# Count elements in an iterable
data = range(100)
count = ilen(data) # 100
# Count elements matching predicate
numbers = [1, 2, 3, 4, 5, 6]
even_count = quantify(numbers, lambda x: x % 2 == 0) # 3Functions for testing properties across all elements.
def all_equal(iterable: Iterable[Any]) -> bool: ...
def all_unique(iterable: Iterable[Any]) -> bool: ...Usage:
from more_itertools import all_equal, all_unique
# Check if all elements are equal
all_equal([1, 1, 1, 1]) # True
all_equal([1, 2, 1, 1]) # False
# Check if all elements are unique
all_unique([1, 2, 3, 4]) # True
all_unique([1, 2, 2, 4]) # FalseFunctions for finding extremes and their positions.
def minmax(iterable: Iterable[Any], *, default=None, key: Callable[[Any], Any] = None) -> tuple[Any, Any]: ...
def argmax(iterable: Iterable[Any], *, default=None, key: Callable[[Any], Any] = None) -> Any: ...
def argmin(iterable: Iterable[Any], *, default=None, key: Callable[[Any], Any] = None) -> Any: ...Usage:
from more_itertools import minmax, argmax, argmin
data = [3, 1, 4, 1, 5, 9, 2]
# Get both min and max in one pass
min_val, max_val = minmax(data) # (1, 9)
# Get index of maximum value
max_index = argmax(data) # 5 (index of value 9)
# Get index of minimum value
min_index = argmin(data) # 1 (index of first occurrence of 1)Class for compressing and decompressing consecutive identical elements.
class run_length:
"""Run-length encoding and decoding operations."""
@staticmethod
def encode(iterable):
"""
Compress iterable with run-length encoding.
Args:
iterable: The iterable to compress
Returns:
Iterator of (item, count) tuples
"""
@staticmethod
def decode(iterable):
"""
Decompress run-length encoded data.
Args:
iterable: Iterator of (item, count) tuples
Returns:
Iterator of decompressed items
"""Usage:
from more_itertools import run_length
# Encode runs of identical elements
data = [1, 1, 1, 2, 2, 3, 3, 3, 3]
encoded = list(run_length.encode(data)) # [(1, 3), (2, 2), (3, 4)]
# Decode back to original
decoded = list(run_length.decode(encoded)) # [1, 1, 1, 2, 2, 3, 3, 3, 3]Install with Tessl CLI
npx tessl i tessl/pypi-more-itertools