import itertools
it = itertools.chain([1, 2, 3], [4, 5, 6])
print(list(it))[1, 2, 3, 4, 5, 6]
itertools for Working with Iterators and Generatorsitertools is a built-in module providing functions for advanced interactions with iteratorsChainchainchain.from_iterable()
repeatcycleteezip_longestzip variant that iterates until the longest iterator is exhaustedfillvalue or Nonezip: [('one', 1), ('two', 2)]
zip_longest: [('one', 1), ('two', 2), ('three', 'nope')]
islicetakewhileFalse
dropwhiledropwhileFalse
filterfalsefilter functionFalseFilter: [2, 4, 6, 8, 10]
Filter false: [1, 3, 5, 7, 9]
batched[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10,)]
pairwise[a, b, c] generates [(a, b), (b, c)]
accumulateimport itertools
# basic example, defaults to sum
values = [i for i in range(1, 11)]
sum_reduce = itertools.accumulate(values)
print("Sum: ", list(sum_reduce))
# advanced example, specifying our own function
def sum_modulo_20(first, second):
output = first + second
return output % 20
modulo_reduce = itertools.accumulate(values, sum_modulo_20)
print("Sum Modulo 20: ", list(modulo_reduce))Sum: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
Sum Modulo 20: [1, 3, 6, 10, 15, 1, 8, 16, 5, 15]
functools reduce function
productrepeat lets you calculate the product of an iterator with repeat - 1 copies of itselfSingle: [(1, 1), (1, 2), (2, 1), (2, 2)]
Multiple: [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c')]
permutationscombinationscombinations_with_replacementcombinations but replacements are allowedpermutations the same value can be repeated in the same output group e.g. (1,1)itertools functions fall into three main categories