Functional Python Programming

(Wang) #1

More Itertools Techniques


Functional programming emphasizes stateless programming. In Python, this leads
us to work with generator expressions, generator functions, and iterables. In this
chapter, we'll continue our study of the itertools library, with numerous functions
to help us work with iterable collections.


In the previous chapter, we looked at three broad groupings of iterator functions.
They are as follows:



  • Functions that work with infinite iterators can be applied to any iterable
    or an iterator over any collection; they will consume the entire source

  • Functions that work with finite iterators can either accumulate a source
    multiple times, or they produce a reduction of the source

  • The tee() iterator function clones an iterator into several copies that can
    each be used independently


In this chapter, we'll look at the itertools functions that work with permutations
and combinations. These include several functions and a few recipes built on these
functions. The functions are as follows:



  • product(): This function forms a Cartesian product equivalent to the nested
    for loops

  • permutations(): This function emits tuples of length r from a universe p in
    all possible orderings; there are no repeated elements

  • combinations(): This function emits tuples of length r from a universe p in
    sorted order; there are no repeated elements

  • combinations_with_replacement(): This function emits tuples of length r
    from p in a sorted order, with repeated elements

Free download pdf