Skip to content

Iterators

Create

Action Code Details
Indefinite counter
itertools.count()
Create counter starting from n
itertools.count(n)
Create counter starting from n with step size s
itertools.count(n, s)
Create limited counter from n to m
?
Repeat constant value v by n times
itertools.repeat(v, n)
2D coordinates grid from (0, 0) to (n - 1, m - 1 )
itertools.product(range(n), range(m))
From string (over chars)
iter(str)
From list
iter(lst)
Enumeration pairs (index, element) from list
enumerate(lst)
From list, indefinitely
itertools.cycle(lst)
From list, n times
itertools.product(lst, n)
Concatenate lists
itertools.chain(lst1, lst2)
Key-value pairs from dict
enumerate(dct)
Create n copies of iterable
itertools.tee(x, 2)
Create n copies of iterable
x1, x2 = itertools.tee(x)

Usage

Action Code Details
Loop over iterator
for i in iter:
    print(i)

Test

Note that all tests consume.

Action Code Details
All elements are true
all(bool_iter)
Any element is true
any(bool_iter)
All elements are false
not any(bool_iter)
Any element is false
not all(bool_iter)
All elements are equal
g = groupby(x)
next(g, True) and not next(g, False)
All elements are true conditional on function
all(map(boolFun, iter))

Extract

Operations (partially) consume the iterable unless mentioned otherwise.

Action Code Details
Get remaining length
sum(1 for _ in iter)
Fully consumes
Next element
next(iter)
Get next element with default if depleted
next(iter, 0)
Get n th element
next(itertools.islice(x, n, None), default)
Get first element according to criterion
next(e for e in x if e == 1)
Get first element according to criterion
next(filter(lambda e: e == 1, x))
Get index of first true element
?
Get index of first false element
?

Update

Action Code Details
Clear (consume fully)
collections.deque(x, maxlen=0)

Derive

Action Code Details
First n items of iterable
itertools.islice(x, n)
Last n items of iterable
iter(collections.deque(x, maxlen = n))
Drop first n items of iterable
itertools.islice(x, start=n)
Drop while predicate is true
itertools.dropwhile(lambda x: x < 5, x)
Slice based on (index) integer iterable
?
Filter based on boolean function
filter(bool_fun, iterable)
Filter based on boolean iterable
itertools.compress(x, mask_iter)
Inverse filter iterable based on a boolean iterable
itertools.filterfalse(mask, x)
Take while predicate is true
itertools.takewhile(lambda x: x < 5, x)
Filter iterables based on boolean function
filter(lambda x: x[0] != x[1], zip(iter1, iter2))

Transform iterable

Using the derived iterable consumes the original one as well.

Action Code Details
Transform elements by expression
x + 1 for x in iter
Map elements with function
map(fun, iter)
Invert boolean iterator
map(lambda x: not x, bool_iter)
Invert boolean iterator
map(operator.not_, bool_iter)
Cumulative sum
itertools.accumulate(iter)
Accumulate function (reduce() with keeping all results)
itertools.accumulate(iter, fun)

Grow

Action Code Details
Append iterable
itertools.chain(iter, append_iter)
Prepend iterable
itertools.chain(prepend_iter, iter)
Cartesian product of two or more iterables
itertools.product(x, y, ...)
Repeat iterable indefinitely
itertools.cycle(x)
Repeat iterable n times
itertools.repeat(x, n)
Repeat each element of iterable n times
itertools.chain.from_iterable(itertools.repeat(tuple(x), n))

Shrink

Combine iterables

Action Code Details
Chain iterables (concatenate)
itertools.chain.from_iterable(x, y, ...)
Combine iterable elements as tuple, stop on shortest iterable
zip(x, y, ...)
Combine iterable elements as tuple, expect equal length
zip(x, y, ..., strict=True)
Throws error if an iterable is depleted prematurely
Combine iterable elements as tuple until all iterables are exhausted, with default value for depleted iterables
itertools.zip_longest(x, y, ..., fillvalue = None)
Create combinations of pairs
itertools.combinations(x, 2)
Create combinations of size n
itertools.combinations(x, n)
Create combinations of size n with replacement
itertools.combinations_with_replacement(x, n)
Create combinations of pairs with replacement (so including pairs of (A, A))
itertools.combinations_with_replacement(x, 2)
Create permutations
itertools.permutations(x)

Convert

Action Code Details
List
list(iter)
Tuple
tuple(iter)
Dict
dict(zip(key_iter, value_iter))