itertools

What it is good for?

Functions to work with lists and iterators.

Most functions in this module return iterators, so you can use their result once or convert it to a list.

Installed with Python by default

yes

Example

Concatenate a list:

  1. import itertools
  2. ch = itertools.chain([1,2],[3,4])
  3. print(list(ch))
  4. [1, 2, 3, 4]
  5. print(list(itertools.repeat([1,2], 3)))
  6. [[1, 2], [1, 2], [1, 2]]

Permutations and combinations of list elements:

  1. p = itertools.permutations([1,2,3])
  2. print(list(p))
  3. [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
  4. c = itertools.combinations([1,2,3], 2)
  5. print(list(c))
  6. [(1, 2), (1, 3), (2, 3)]

Where to learn more?

https://docs.python.org/3/library/itertools.html