Itertools

The itertools module provides a collection of tools for working with iterators that operate on sequence items. These tools help create iterators for efficient looping.


import itertools

# Returning an iterator that repeats a given value a specific number of times
repeated = itertools.repeat(10, 3) # value, number of times
for x in repeated:
    print(x)

# Combining multiple iterables into one continuous sequence
chained = itertools.chain([1, 2], ["a", "b"], [True, False])
for item in chained:
    print(item) 

# Returning n-length tuples with combinations of elements from the iterable (sorted in lexicographical order)
combs = itertools.combinations("ABCD", 2) # iterable, n
for comb in combs:
    print(comb)

# The same as combinations(), but each arrangement of elements is treated as a unique permutation (order matters), e.g., ('A', 'B') and ('B', 'A') are treated as different
perms = itertools.permutations("ABCD", 2)
for perm in perms:
    print(perm)