Library for Working with Iterators

The built-in itertools package (https://docs.python.org/3/library/itertools.html) contains a collection of useful iterators. Let's talk about a few of them:

  • combinations — returns a tuple in sorted order without repeated elements.
  • chain — returns elements from an object until it's exhausted, then proceeds to the next one, used to handle multiple sequences as a single one.
  • permutations — returns all possible permutations.
  • filterfalse — returns all elements for which the function returned false.
  • starmap — applies a function to each element of a sequence, unpacking it.

Many more are in the library, so I recommend checking out the documentation.

import itertools

print(list(itertools.combinations("ABCD", 2)))
# Output: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

print(list(itertools.chain(['1,2,3'], [4,5,6])))
# Output: ['1,2,3', 4, 5, 6]

print(list(itertools.permutations("ABC", 2)))
# Output: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

print(list(itertools.filterfalse(lambda x: x==100, [1,2,3,4,5])))
# Output: [1, 2, 3, 4, 5]

print(list(itertools.starmap(pow, [(2,2), (2,3), (2,4)])))
# Output: [4, 8, 16]

Comments (0)

Leave a comment