1********************************
2  Functional Programming HOWTO
3********************************
4
5:Author: A. M. Kuchling
6:Release: 0.32
7
8In this document, we'll take a tour of Python's features suitable for
9implementing programs in a functional style.  After an introduction to the
10concepts of functional programming, we'll look at language features such as
11:term:`iterator`\s and :term:`generator`\s and relevant library modules such as
12:mod:`itertools` and :mod:`functools`.
13
14
15Introduction
16============
17
18This section explains the basic concept of functional programming; if
19you're just interested in learning about Python language features,
20skip to the next section on :ref:`functional-howto-iterators`.
21
22Programming languages support decomposing problems in several different ways:
23
24* Most programming languages are **procedural**: programs are lists of
25  instructions that tell the computer what to do with the program's input.  C,
26  Pascal, and even Unix shells are procedural languages.
27
28* In **declarative** languages, you write a specification that describes the
29  problem to be solved, and the language implementation figures out how to
30  perform the computation efficiently.  SQL is the declarative language you're
31  most likely to be familiar with; a SQL query describes the data set you want
32  to retrieve, and the SQL engine decides whether to scan tables or use indexes,
33  which subclauses should be performed first, etc.
34
35* **Object-oriented** programs manipulate collections of objects.  Objects have
36  internal state and support methods that query or modify this internal state in
37  some way. Smalltalk and Java are object-oriented languages.  C++ and Python
38  are languages that support object-oriented programming, but don't force the
39  use of object-oriented features.
40
41* **Functional** programming decomposes a problem into a set of functions.
42  Ideally, functions only take inputs and produce outputs, and don't have any
43  internal state that affects the output produced for a given input.  Well-known
44  functional languages include the ML family (Standard ML, OCaml, and other
45  variants) and Haskell.
46
47The designers of some computer languages choose to emphasize one
48particular approach to programming.  This often makes it difficult to
49write programs that use a different approach.  Other languages are
50multi-paradigm languages that support several different approaches.
51Lisp, C++, and Python are multi-paradigm; you can write programs or
52libraries that are largely procedural, object-oriented, or functional
53in all of these languages.  In a large program, different sections
54might be written using different approaches; the GUI might be
55object-oriented while the processing logic is procedural or
56functional, for example.
57
58In a functional program, input flows through a set of functions. Each function
59operates on its input and produces some output.  Functional style discourages
60functions with side effects that modify internal state or make other changes
61that aren't visible in the function's return value.  Functions that have no side
62effects at all are called **purely functional**.  Avoiding side effects means
63not using data structures that get updated as a program runs; every function's
64output must only depend on its input.
65
66Some languages are very strict about purity and don't even have assignment
67statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all
68side effects, such as printing to the screen or writing to a disk file. Another
69example is a call to the :func:`print` or :func:`time.sleep` function, neither
70of which returns a useful value. Both are called only for their side effects
71of sending some text to the screen or pausing execution for a second.
72
73Python programs written in functional style usually won't go to the extreme of
74avoiding all I/O or all assignments; instead, they'll provide a
75functional-appearing interface but will use non-functional features internally.
76For example, the implementation of a function will still use assignments to
77local variables, but won't modify global variables or have other side effects.
78
79Functional programming can be considered the opposite of object-oriented
80programming.  Objects are little capsules containing some internal state along
81with a collection of method calls that let you modify this state, and programs
82consist of making the right set of state changes.  Functional programming wants
83to avoid state changes as much as possible and works with data flowing between
84functions.  In Python you might combine the two approaches by writing functions
85that take and return instances representing objects in your application (e-mail
86messages, transactions, etc.).
87
88Functional design may seem like an odd constraint to work under.  Why should you
89avoid objects and side effects?  There are theoretical and practical advantages
90to the functional style:
91
92* Formal provability.
93* Modularity.
94* Composability.
95* Ease of debugging and testing.
96
97
98Formal provability
99------------------
100
101A theoretical benefit is that it's easier to construct a mathematical proof that
102a functional program is correct.
103
104For a long time researchers have been interested in finding ways to
105mathematically prove programs correct.  This is different from testing a program
106on numerous inputs and concluding that its output is usually correct, or reading
107a program's source code and concluding that the code looks right; the goal is
108instead a rigorous proof that a program produces the right result for all
109possible inputs.
110
111The technique used to prove programs correct is to write down **invariants**,
112properties of the input data and of the program's variables that are always
113true.  For each line of code, you then show that if invariants X and Y are true
114**before** the line is executed, the slightly different invariants X' and Y' are
115true **after** the line is executed.  This continues until you reach the end of
116the program, at which point the invariants should match the desired conditions
117on the program's output.
118
119Functional programming's avoidance of assignments arose because assignments are
120difficult to handle with this technique; assignments can break invariants that
121were true before the assignment without producing any new invariants that can be
122propagated onward.
123
124Unfortunately, proving programs correct is largely impractical and not relevant
125to Python software. Even trivial programs require proofs that are several pages
126long; the proof of correctness for a moderately complicated program would be
127enormous, and few or none of the programs you use daily (the Python interpreter,
128your XML parser, your web browser) could be proven correct.  Even if you wrote
129down or generated a proof, there would then be the question of verifying the
130proof; maybe there's an error in it, and you wrongly believe you've proved the
131program correct.
132
133
134Modularity
135----------
136
137A more practical benefit of functional programming is that it forces you to
138break apart your problem into small pieces.  Programs are more modular as a
139result.  It's easier to specify and write a small function that does one thing
140than a large function that performs a complicated transformation.  Small
141functions are also easier to read and to check for errors.
142
143
144Ease of debugging and testing
145-----------------------------
146
147Testing and debugging a functional-style program is easier.
148
149Debugging is simplified because functions are generally small and clearly
150specified.  When a program doesn't work, each function is an interface point
151where you can check that the data are correct.  You can look at the intermediate
152inputs and outputs to quickly isolate the function that's responsible for a bug.
153
154Testing is easier because each function is a potential subject for a unit test.
155Functions don't depend on system state that needs to be replicated before
156running a test; instead you only have to synthesize the right input and then
157check that the output matches expectations.
158
159
160Composability
161-------------
162
163As you work on a functional-style program, you'll write a number of functions
164with varying inputs and outputs.  Some of these functions will be unavoidably
165specialized to a particular application, but others will be useful in a wide
166variety of programs.  For example, a function that takes a directory path and
167returns all the XML files in the directory, or a function that takes a filename
168and returns its contents, can be applied to many different situations.
169
170Over time you'll form a personal library of utilities.  Often you'll assemble
171new programs by arranging existing functions in a new configuration and writing
172a few functions specialized for the current task.
173
174
175.. _functional-howto-iterators:
176
177Iterators
178=========
179
180I'll start by looking at a Python language feature that's an important
181foundation for writing functional-style programs: iterators.
182
183An iterator is an object representing a stream of data; this object returns the
184data one element at a time.  A Python iterator must support a method called
185:meth:`~iterator.__next__` that takes no arguments and always returns the next
186element of the stream.  If there are no more elements in the stream,
187:meth:`~iterator.__next__` must raise the :exc:`StopIteration` exception.
188Iterators don't have to be finite, though; it's perfectly reasonable to write
189an iterator that produces an infinite stream of data.
190
191The built-in :func:`iter` function takes an arbitrary object and tries to return
192an iterator that will return the object's contents or elements, raising
193:exc:`TypeError` if the object doesn't support iteration.  Several of Python's
194built-in data types support iteration, the most common being lists and
195dictionaries.  An object is called :term:`iterable` if you can get an iterator
196for it.
197
198You can experiment with the iteration interface manually:
199
200    >>> L = [1, 2, 3]
201    >>> it = iter(L)
202    >>> it  #doctest: +ELLIPSIS
203    <...iterator object at ...>
204    >>> it.__next__()  # same as next(it)
205    1
206    >>> next(it)
207    2
208    >>> next(it)
209    3
210    >>> next(it)
211    Traceback (most recent call last):
212      File "<stdin>", line 1, in <module>
213    StopIteration
214    >>>
215
216Python expects iterable objects in several different contexts, the most
217important being the :keyword:`for` statement.  In the statement ``for X in Y``,
218Y must be an iterator or some object for which :func:`iter` can create an
219iterator.  These two statements are equivalent::
220
221
222    for i in iter(obj):
223        print(i)
224
225    for i in obj:
226        print(i)
227
228Iterators can be materialized as lists or tuples by using the :func:`list` or
229:func:`tuple` constructor functions:
230
231    >>> L = [1, 2, 3]
232    >>> iterator = iter(L)
233    >>> t = tuple(iterator)
234    >>> t
235    (1, 2, 3)
236
237Sequence unpacking also supports iterators: if you know an iterator will return
238N elements, you can unpack them into an N-tuple:
239
240    >>> L = [1, 2, 3]
241    >>> iterator = iter(L)
242    >>> a, b, c = iterator
243    >>> a, b, c
244    (1, 2, 3)
245
246Built-in functions such as :func:`max` and :func:`min` can take a single
247iterator argument and will return the largest or smallest element.  The ``"in"``
248and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
249X is found in the stream returned by the iterator.  You'll run into obvious
250problems if the iterator is infinite; :func:`max`, :func:`min`
251will never return, and if the element X never appears in the stream, the
252``"in"`` and ``"not in"`` operators won't return either.
253
254Note that you can only go forward in an iterator; there's no way to get the
255previous element, reset the iterator, or make a copy of it.  Iterator objects
256can optionally provide these additional capabilities, but the iterator protocol
257only specifies the :meth:`~iterator.__next__` method.  Functions may therefore
258consume all of the iterator's output, and if you need to do something different
259with the same stream, you'll have to create a new iterator.
260
261
262
263Data Types That Support Iterators
264---------------------------------
265
266We've already seen how lists and tuples support iterators.  In fact, any Python
267sequence type, such as strings, will automatically support creation of an
268iterator.
269
270Calling :func:`iter` on a dictionary returns an iterator that will loop over the
271dictionary's keys::
272
273    >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
274    ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
275    >>> for key in m:
276    ...     print(key, m[key])
277    Jan 1
278    Feb 2
279    Mar 3
280    Apr 4
281    May 5
282    Jun 6
283    Jul 7
284    Aug 8
285    Sep 9
286    Oct 10
287    Nov 11
288    Dec 12
289
290Note that starting with Python 3.7, dictionary iteration order is guaranteed
291to be the same as the insertion order. In earlier versions, the behaviour was
292unspecified and could vary between implementations.
293
294Applying :func:`iter` to a dictionary always loops over the keys, but
295dictionaries have methods that return other iterators.  If you want to iterate
296over values or key/value pairs, you can explicitly call the
297:meth:`~dict.values` or :meth:`~dict.items` methods to get an appropriate
298iterator.
299
300The :func:`dict` constructor can accept an iterator that returns a finite stream
301of ``(key, value)`` tuples:
302
303    >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
304    >>> dict(iter(L))
305    {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
306
307Files also support iteration by calling the :meth:`~io.TextIOBase.readline`
308method until there are no more lines in the file.  This means you can read each
309line of a file like this::
310
311    for line in file:
312        # do something for each line
313        ...
314
315Sets can take their contents from an iterable and let you iterate over the set's
316elements::
317
318    >>> S = {2, 3, 5, 7, 11, 13}
319    >>> for i in S:
320    ...     print(i)
321    2
322    3
323    5
324    7
325    11
326    13
327
328
329
330Generator expressions and list comprehensions
331=============================================
332
333Two common operations on an iterator's output are 1) performing some operation
334for every element, 2) selecting a subset of elements that meet some condition.
335For example, given a list of strings, you might want to strip off trailing
336whitespace from each line or extract all the strings containing a given
337substring.
338
339List comprehensions and generator expressions (short form: "listcomps" and
340"genexps") are a concise notation for such operations, borrowed from the
341functional programming language Haskell (https://www.haskell.org/).  You can strip
342all the whitespace from a stream of strings with the following code::
343
344    >>> line_list = ['  line 1\n', 'line 2  \n', ' \n', '']
345
346    >>> # Generator expression -- returns iterator
347    >>> stripped_iter = (line.strip() for line in line_list)
348
349    >>> # List comprehension -- returns list
350    >>> stripped_list = [line.strip() for line in line_list]
351
352You can select only certain elements by adding an ``"if"`` condition::
353
354    >>> stripped_list = [line.strip() for line in line_list
355    ...                  if line != ""]
356
357With a list comprehension, you get back a Python list; ``stripped_list`` is a
358list containing the resulting lines, not an iterator.  Generator expressions
359return an iterator that computes the values as necessary, not needing to
360materialize all the values at once.  This means that list comprehensions aren't
361useful if you're working with iterators that return an infinite stream or a very
362large amount of data.  Generator expressions are preferable in these situations.
363
364Generator expressions are surrounded by parentheses ("()") and list
365comprehensions are surrounded by square brackets ("[]").  Generator expressions
366have the form::
367
368    ( expression for expr in sequence1
369                 if condition1
370                 for expr2 in sequence2
371                 if condition2
372                 for expr3 in sequence3
373                 ...
374                 if condition3
375                 for exprN in sequenceN
376                 if conditionN )
377
378Again, for a list comprehension only the outside brackets are different (square
379brackets instead of parentheses).
380
381The elements of the generated output will be the successive values of
382``expression``.  The ``if`` clauses are all optional; if present, ``expression``
383is only evaluated and added to the result when ``condition`` is true.
384
385Generator expressions always have to be written inside parentheses, but the
386parentheses signalling a function call also count.  If you want to create an
387iterator that will be immediately passed to a function you can write::
388
389    obj_total = sum(obj.count for obj in list_all_objects())
390
391The ``for...in`` clauses contain the sequences to be iterated over.  The
392sequences do not have to be the same length, because they are iterated over from
393left to right, **not** in parallel.  For each element in ``sequence1``,
394``sequence2`` is looped over from the beginning.  ``sequence3`` is then looped
395over for each resulting pair of elements from ``sequence1`` and ``sequence2``.
396
397To put it another way, a list comprehension or generator expression is
398equivalent to the following Python code::
399
400    for expr1 in sequence1:
401        if not (condition1):
402            continue   # Skip this element
403        for expr2 in sequence2:
404            if not (condition2):
405                continue   # Skip this element
406            ...
407            for exprN in sequenceN:
408                if not (conditionN):
409                    continue   # Skip this element
410
411                # Output the value of
412                # the expression.
413
414This means that when there are multiple ``for...in`` clauses but no ``if``
415clauses, the length of the resulting output will be equal to the product of the
416lengths of all the sequences.  If you have two lists of length 3, the output
417list is 9 elements long:
418
419    >>> seq1 = 'abc'
420    >>> seq2 = (1, 2, 3)
421    >>> [(x, y) for x in seq1 for y in seq2]  #doctest: +NORMALIZE_WHITESPACE
422    [('a', 1), ('a', 2), ('a', 3),
423     ('b', 1), ('b', 2), ('b', 3),
424     ('c', 1), ('c', 2), ('c', 3)]
425
426To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
427creating a tuple, it must be surrounded with parentheses.  The first list
428comprehension below is a syntax error, while the second one is correct::
429
430    # Syntax error
431    [x, y for x in seq1 for y in seq2]
432    # Correct
433    [(x, y) for x in seq1 for y in seq2]
434
435
436Generators
437==========
438
439Generators are a special class of functions that simplify the task of writing
440iterators.  Regular functions compute a value and return it, but generators
441return an iterator that returns a stream of values.
442
443You're doubtless familiar with how regular function calls work in Python or C.
444When you call a function, it gets a private namespace where its local variables
445are created.  When the function reaches a ``return`` statement, the local
446variables are destroyed and the value is returned to the caller.  A later call
447to the same function creates a new private namespace and a fresh set of local
448variables. But, what if the local variables weren't thrown away on exiting a
449function?  What if you could later resume the function where it left off?  This
450is what generators provide; they can be thought of as resumable functions.
451
452Here's the simplest example of a generator function:
453
454    >>> def generate_ints(N):
455    ...    for i in range(N):
456    ...        yield i
457
458Any function containing a :keyword:`yield` keyword is a generator function;
459this is detected by Python's :term:`bytecode` compiler which compiles the
460function specially as a result.
461
462When you call a generator function, it doesn't return a single value; instead it
463returns a generator object that supports the iterator protocol.  On executing
464the ``yield`` expression, the generator outputs the value of ``i``, similar to a
465``return`` statement.  The big difference between ``yield`` and a ``return``
466statement is that on reaching a ``yield`` the generator's state of execution is
467suspended and local variables are preserved.  On the next call to the
468generator's :meth:`~generator.__next__` method, the function will resume
469executing.
470
471Here's a sample usage of the ``generate_ints()`` generator:
472
473    >>> gen = generate_ints(3)
474    >>> gen  #doctest: +ELLIPSIS
475    <generator object generate_ints at ...>
476    >>> next(gen)
477    0
478    >>> next(gen)
479    1
480    >>> next(gen)
481    2
482    >>> next(gen)
483    Traceback (most recent call last):
484      File "stdin", line 1, in <module>
485      File "stdin", line 2, in generate_ints
486    StopIteration
487
488You could equally write ``for i in generate_ints(5)``, or ``a, b, c =
489generate_ints(3)``.
490
491Inside a generator function, ``return value`` causes ``StopIteration(value)``
492to be raised from the :meth:`~generator.__next__` method.  Once this happens, or
493the bottom of the function is reached, the procession of values ends and the
494generator cannot yield any further values.
495
496You could achieve the effect of generators manually by writing your own class
497and storing all the local variables of the generator as instance variables.  For
498example, returning a list of integers could be done by setting ``self.count`` to
4990, and having the :meth:`~iterator.__next__` method increment ``self.count`` and
500return it.
501However, for a moderately complicated generator, writing a corresponding class
502can be much messier.
503
504The test suite included with Python's library,
505:source:`Lib/test/test_generators.py`, contains
506a number of more interesting examples.  Here's one generator that implements an
507in-order traversal of a tree using generators recursively. ::
508
509    # A recursive generator that generates Tree leaves in in-order.
510    def inorder(t):
511        if t:
512            for x in inorder(t.left):
513                yield x
514
515            yield t.label
516
517            for x in inorder(t.right):
518                yield x
519
520Two other examples in ``test_generators.py`` produce solutions for the N-Queens
521problem (placing N queens on an NxN chess board so that no queen threatens
522another) and the Knight's Tour (finding a route that takes a knight to every
523square of an NxN chessboard without visiting any square twice).
524
525
526
527Passing values into a generator
528-------------------------------
529
530In Python 2.4 and earlier, generators only produced output.  Once a generator's
531code was invoked to create an iterator, there was no way to pass any new
532information into the function when its execution is resumed.  You could hack
533together this ability by making the generator look at a global variable or by
534passing in some mutable object that callers then modify, but these approaches
535are messy.
536
537In Python 2.5 there's a simple way to pass values into a generator.
538:keyword:`yield` became an expression, returning a value that can be assigned to
539a variable or otherwise operated on::
540
541    val = (yield i)
542
543I recommend that you **always** put parentheses around a ``yield`` expression
544when you're doing something with the returned value, as in the above example.
545The parentheses aren't always necessary, but it's easier to always add them
546instead of having to remember when they're needed.
547
548(:pep:`342` explains the exact rules, which are that a ``yield``-expression must
549always be parenthesized except when it occurs at the top-level expression on the
550right-hand side of an assignment.  This means you can write ``val = yield i``
551but have to use parentheses when there's an operation, as in ``val = (yield i)
552+ 12``.)
553
554Values are sent into a generator by calling its :meth:`send(value)
555<generator.send>` method.  This method resumes the generator's code and the
556``yield`` expression returns the specified value.  If the regular
557:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``.
558
559Here's a simple counter that increments by 1 and allows changing the value of
560the internal counter.
561
562.. testcode::
563
564    def counter(maximum):
565        i = 0
566        while i < maximum:
567            val = (yield i)
568            # If value provided, change counter
569            if val is not None:
570                i = val
571            else:
572                i += 1
573
574And here's an example of changing the counter:
575
576    >>> it = counter(10)  #doctest: +SKIP
577    >>> next(it)  #doctest: +SKIP
578    0
579    >>> next(it)  #doctest: +SKIP
580    1
581    >>> it.send(8)  #doctest: +SKIP
582    8
583    >>> next(it)  #doctest: +SKIP
584    9
585    >>> next(it)  #doctest: +SKIP
586    Traceback (most recent call last):
587      File "t.py", line 15, in <module>
588        it.next()
589    StopIteration
590
591Because ``yield`` will often be returning ``None``, you should always check for
592this case.  Don't just use its value in expressions unless you're sure that the
593:meth:`~generator.send` method will be the only method used to resume your
594generator function.
595
596In addition to :meth:`~generator.send`, there are two other methods on
597generators:
598
599* :meth:`throw(value) <generator.throw>` is used to
600  raise an exception inside the generator; the exception is raised by the
601  ``yield`` expression where the generator's execution is paused.
602
603* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the
604  generator to terminate the iteration.  On receiving this exception, the
605  generator's code must either raise :exc:`GeneratorExit` or
606  :exc:`StopIteration`; catching the exception and doing anything else is
607  illegal and will trigger a :exc:`RuntimeError`.  :meth:`~generator.close`
608  will also be called by Python's garbage collector when the generator is
609  garbage-collected.
610
611  If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
612  using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
613
614The cumulative effect of these changes is to turn generators from one-way
615producers of information into both producers and consumers.
616
617Generators also become **coroutines**, a more generalized form of subroutines.
618Subroutines are entered at one point and exited at another point (the top of the
619function, and a ``return`` statement), but coroutines can be entered, exited,
620and resumed at many different points (the ``yield`` statements).
621
622
623Built-in functions
624==================
625
626Let's look in more detail at built-in functions often used with iterators.
627
628Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
629features of generator expressions:
630
631:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence
632 ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
633
634    >>> def upper(s):
635    ...     return s.upper()
636
637    >>> list(map(upper, ['sentence', 'fragment']))
638    ['SENTENCE', 'FRAGMENT']
639    >>> [upper(s) for s in ['sentence', 'fragment']]
640    ['SENTENCE', 'FRAGMENT']
641
642You can of course achieve the same effect with a list comprehension.
643
644:func:`filter(predicate, iter) <filter>` returns an iterator over all the
645sequence elements that meet a certain condition, and is similarly duplicated by
646list comprehensions.  A **predicate** is a function that returns the truth
647value of some condition; for use with :func:`filter`, the predicate must take a
648single value.
649
650    >>> def is_even(x):
651    ...     return (x % 2) == 0
652
653    >>> list(filter(is_even, range(10)))
654    [0, 2, 4, 6, 8]
655
656
657This can also be written as a list comprehension:
658
659    >>> list(x for x in range(10) if is_even(x))
660    [0, 2, 4, 6, 8]
661
662
663:func:`enumerate(iter, start=0) <enumerate>` counts off the elements in the
664iterable returning 2-tuples containing the count (from *start*) and
665each element. ::
666
667    >>> for item in enumerate(['subject', 'verb', 'object']):
668    ...     print(item)
669    (0, 'subject')
670    (1, 'verb')
671    (2, 'object')
672
673:func:`enumerate` is often used when looping through a list and recording the
674indexes at which certain conditions are met::
675
676    f = open('data.txt', 'r')
677    for i, line in enumerate(f):
678        if line.strip() == '':
679            print('Blank line at line #%i' % i)
680
681:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the
682elements of the iterable into a list, sorts the list, and returns the sorted
683result.  The *key* and *reverse* arguments are passed through to the
684constructed list's :meth:`~list.sort` method. ::
685
686    >>> import random
687    >>> # Generate 8 random numbers between [0, 10000)
688    >>> rand_list = random.sample(range(10000), 8)
689    >>> rand_list  #doctest: +SKIP
690    [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
691    >>> sorted(rand_list)  #doctest: +SKIP
692    [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
693    >>> sorted(rand_list, reverse=True)  #doctest: +SKIP
694    [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
695
696(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)
697
698
699The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the
700truth values of an iterable's contents.  :func:`any` returns ``True`` if any element
701in the iterable is a true value, and :func:`all` returns ``True`` if all of the
702elements are true values:
703
704    >>> any([0, 1, 0])
705    True
706    >>> any([0, 0, 0])
707    False
708    >>> any([1, 1, 1])
709    True
710    >>> all([0, 1, 0])
711    False
712    >>> all([0, 0, 0])
713    False
714    >>> all([1, 1, 1])
715    True
716
717
718:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and
719returns them in a tuple::
720
721    zip(['a', 'b', 'c'], (1, 2, 3)) =>
722      ('a', 1), ('b', 2), ('c', 3)
723
724It doesn't construct an in-memory list and exhaust all the input iterators
725before returning; instead tuples are constructed and returned only if they're
726requested.  (The technical term for this behaviour is `lazy evaluation
727<https://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
728
729This iterator is intended to be used with iterables that are all of the same
730length.  If the iterables are of different lengths, the resulting stream will be
731the same length as the shortest iterable. ::
732
733    zip(['a', 'b'], (1, 2, 3)) =>
734      ('a', 1), ('b', 2)
735
736You should avoid doing this, though, because an element may be taken from the
737longer iterators and discarded.  This means you can't go on to use the iterators
738further because you risk skipping a discarded element.
739
740
741The itertools module
742====================
743
744The :mod:`itertools` module contains a number of commonly used iterators as well
745as functions for combining several iterators.  This section will introduce the
746module's contents by showing small examples.
747
748The module's functions fall into a few broad classes:
749
750* Functions that create a new iterator based on an existing iterator.
751* Functions for treating an iterator's elements as function arguments.
752* Functions for selecting portions of an iterator's output.
753* A function for grouping an iterator's output.
754
755Creating new iterators
756----------------------
757
758:func:`itertools.count(start, step) <itertools.count>` returns an infinite
759stream of evenly spaced values.  You can optionally supply the starting number,
760which defaults to 0, and the interval between numbers, which defaults to 1::
761
762    itertools.count() =>
763      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
764    itertools.count(10) =>
765      10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
766    itertools.count(10, 5) =>
767      10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
768
769:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of
770a provided iterable and returns a new iterator that returns its elements from
771first to last.  The new iterator will repeat these elements infinitely. ::
772
773    itertools.cycle([1, 2, 3, 4, 5]) =>
774      1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
775
776:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided
777element *n* times, or returns the element endlessly if *n* is not provided. ::
778
779    itertools.repeat('abc') =>
780      abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
781    itertools.repeat('abc', 5) =>
782      abc, abc, abc, abc, abc
783
784:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary
785number of iterables as input, and returns all the elements of the first
786iterator, then all the elements of the second, and so on, until all of the
787iterables have been exhausted. ::
788
789    itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
790      a, b, c, 1, 2, 3
791
792:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns
793a stream that's a slice of the iterator.  With a single *stop* argument, it
794will return the first *stop* elements.  If you supply a starting index, you'll
795get *stop-start* elements, and if you supply a value for *step*, elements
796will be skipped accordingly.  Unlike Python's string and list slicing, you can't
797use negative values for *start*, *stop*, or *step*. ::
798
799    itertools.islice(range(10), 8) =>
800      0, 1, 2, 3, 4, 5, 6, 7
801    itertools.islice(range(10), 2, 8) =>
802      2, 3, 4, 5, 6, 7
803    itertools.islice(range(10), 2, 8, 2) =>
804      2, 4, 6
805
806:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it
807returns *n* independent iterators that will all return the contents of the
808source iterator.
809If you don't supply a value for *n*, the default is 2.  Replicating iterators
810requires saving some of the contents of the source iterator, so this can consume
811significant memory if the iterator is large and one of the new iterators is
812consumed more than the others. ::
813
814        itertools.tee( itertools.count() ) =>
815           iterA, iterB
816
817        where iterA ->
818           0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
819
820        and   iterB ->
821           0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
822
823
824Calling functions on elements
825-----------------------------
826
827The :mod:`operator` module contains a set of functions corresponding to Python's
828operators.  Some examples are :func:`operator.add(a, b) <operator.add>` (adds
829two values), :func:`operator.ne(a, b)  <operator.ne>` (same as ``a != b``), and
830:func:`operator.attrgetter('id') <operator.attrgetter>`
831(returns a callable that fetches the ``.id`` attribute).
832
833:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the
834iterable will return a stream of tuples, and calls *func* using these tuples as
835the arguments::
836
837    itertools.starmap(os.path.join,
838                      [('/bin', 'python'), ('/usr', 'bin', 'java'),
839                       ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
840    =>
841      /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
842
843
844Selecting elements
845------------------
846
847Another group of functions chooses a subset of an iterator's elements based on a
848predicate.
849
850:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the
851opposite of :func:`filter`, returning all elements for which the predicate
852returns false::
853
854    itertools.filterfalse(is_even, itertools.count()) =>
855      1, 3, 5, 7, 9, 11, 13, 15, ...
856
857:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns
858elements for as long as the predicate returns true.  Once the predicate returns
859false, the iterator will signal the end of its results. ::
860
861    def less_than_10(x):
862        return x < 10
863
864    itertools.takewhile(less_than_10, itertools.count()) =>
865      0, 1, 2, 3, 4, 5, 6, 7, 8, 9
866
867    itertools.takewhile(is_even, itertools.count()) =>
868      0
869
870:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards
871elements while the predicate returns true, and then returns the rest of the
872iterable's results. ::
873
874    itertools.dropwhile(less_than_10, itertools.count()) =>
875      10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
876
877    itertools.dropwhile(is_even, itertools.count()) =>
878      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
879
880:func:`itertools.compress(data, selectors) <itertools.compress>` takes two
881iterators and returns only those elements of *data* for which the corresponding
882element of *selectors* is true, stopping whenever either one is exhausted::
883
884    itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
885       1, 2, 5
886
887
888Combinatoric functions
889----------------------
890
891The :func:`itertools.combinations(iterable, r) <itertools.combinations>`
892returns an iterator giving all possible *r*-tuple combinations of the
893elements contained in *iterable*.  ::
894
895    itertools.combinations([1, 2, 3, 4, 5], 2) =>
896      (1, 2), (1, 3), (1, 4), (1, 5),
897      (2, 3), (2, 4), (2, 5),
898      (3, 4), (3, 5),
899      (4, 5)
900
901    itertools.combinations([1, 2, 3, 4, 5], 3) =>
902      (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
903      (2, 3, 4), (2, 3, 5), (2, 4, 5),
904      (3, 4, 5)
905
906The elements within each tuple remain in the same order as
907*iterable* returned them.  For example, the number 1 is always before
9082, 3, 4, or 5 in the examples above.  A similar function,
909:func:`itertools.permutations(iterable, r=None) <itertools.permutations>`,
910removes this constraint on the order, returning all possible
911arrangements of length *r*::
912
913    itertools.permutations([1, 2, 3, 4, 5], 2) =>
914      (1, 2), (1, 3), (1, 4), (1, 5),
915      (2, 1), (2, 3), (2, 4), (2, 5),
916      (3, 1), (3, 2), (3, 4), (3, 5),
917      (4, 1), (4, 2), (4, 3), (4, 5),
918      (5, 1), (5, 2), (5, 3), (5, 4)
919
920    itertools.permutations([1, 2, 3, 4, 5]) =>
921      (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
922      ...
923      (5, 4, 3, 2, 1)
924
925If you don't supply a value for *r* the length of the iterable is used,
926meaning that all the elements are permuted.
927
928Note that these functions produce all of the possible combinations by
929position and don't require that the contents of *iterable* are unique::
930
931    itertools.permutations('aba', 3) =>
932      ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
933      ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
934
935The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a'
936strings came from different positions.
937
938The :func:`itertools.combinations_with_replacement(iterable, r) <itertools.combinations_with_replacement>`
939function relaxes a different constraint: elements can be repeated
940within a single tuple.  Conceptually an element is selected for the
941first position of each tuple and then is replaced before the second
942element is selected.  ::
943
944    itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
945      (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
946      (2, 2), (2, 3), (2, 4), (2, 5),
947      (3, 3), (3, 4), (3, 5),
948      (4, 4), (4, 5),
949      (5, 5)
950
951
952Grouping elements
953-----------------
954
955The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None)
956<itertools.groupby>`, is the most complicated.  ``key_func(elem)`` is a function
957that can compute a key value for each element returned by the iterable.  If you
958don't supply a key function, the key is simply each element itself.
959
960:func:`~itertools.groupby` collects all the consecutive elements from the
961underlying iterable that have the same key value, and returns a stream of
9622-tuples containing a key value and an iterator for the elements with that key.
963
964::
965
966    city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
967                 ('Anchorage', 'AK'), ('Nome', 'AK'),
968                 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
969                 ...
970                ]
971
972    def get_state(city_state):
973        return city_state[1]
974
975    itertools.groupby(city_list, get_state) =>
976      ('AL', iterator-1),
977      ('AK', iterator-2),
978      ('AZ', iterator-3), ...
979
980    where
981    iterator-1 =>
982      ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
983    iterator-2 =>
984      ('Anchorage', 'AK'), ('Nome', 'AK')
985    iterator-3 =>
986      ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
987
988:func:`~itertools.groupby` assumes that the underlying iterable's contents will
989already be sorted based on the key.  Note that the returned iterators also use
990the underlying iterable, so you have to consume the results of iterator-1 before
991requesting iterator-2 and its corresponding key.
992
993
994The functools module
995====================
996
997The :mod:`functools` module contains some higher-order functions.
998A **higher-order function** takes one or more functions as input and returns a
999new function.  The most useful tool in this module is the
1000:func:`functools.partial` function.
1001
1002For programs written in a functional style, you'll sometimes want to construct
1003variants of existing functions that have some of the parameters filled in.
1004Consider a Python function ``f(a, b, c)``; you may wish to create a new function
1005``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
1006one of ``f()``'s parameters.  This is called "partial function application".
1007
1008The constructor for :func:`~functools.partial` takes the arguments
1009``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``.  The resulting
1010object is callable, so you can just call it to invoke ``function`` with the
1011filled-in arguments.
1012
1013Here's a small but realistic example::
1014
1015    import functools
1016
1017    def log(message, subsystem):
1018        """Write the contents of 'message' to the specified subsystem."""
1019        print('%s: %s' % (subsystem, message))
1020        ...
1021
1022    server_log = functools.partial(log, subsystem='server')
1023    server_log('Unable to open socket')
1024
1025:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>`
1026cumulatively performs an operation on all the iterable's elements and,
1027therefore, can't be applied to infinite iterables. *func* must be a function
1028that takes two elements and returns a single value.  :func:`functools.reduce`
1029takes the first two elements A and B returned by the iterator and calculates
1030``func(A, B)``.  It then requests the third element, C, calculates
1031``func(func(A, B), C)``, combines this result with the fourth element returned,
1032and continues until the iterable is exhausted.  If the iterable returns no
1033values at all, a :exc:`TypeError` exception is raised.  If the initial value is
1034supplied, it's used as a starting point and ``func(initial_value, A)`` is the
1035first calculation. ::
1036
1037    >>> import operator, functools
1038    >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
1039    'ABBC'
1040    >>> functools.reduce(operator.concat, [])
1041    Traceback (most recent call last):
1042      ...
1043    TypeError: reduce() of empty sequence with no initial value
1044    >>> functools.reduce(operator.mul, [1, 2, 3], 1)
1045    6
1046    >>> functools.reduce(operator.mul, [], 1)
1047    1
1048
1049If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the
1050elements of the iterable.  This case is so common that there's a special
1051built-in called :func:`sum` to compute it:
1052
1053    >>> import functools, operator
1054    >>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
1055    10
1056    >>> sum([1, 2, 3, 4])
1057    10
1058    >>> sum([])
1059    0
1060
1061For many uses of :func:`functools.reduce`, though, it can be clearer to just
1062write the obvious :keyword:`for` loop::
1063
1064   import functools
1065   # Instead of:
1066   product = functools.reduce(operator.mul, [1, 2, 3], 1)
1067
1068   # You can write:
1069   product = 1
1070   for i in [1, 2, 3]:
1071       product *= i
1072
1073A related function is :func:`itertools.accumulate(iterable, func=operator.add)
1074<itertools.accumulate>`.  It performs the same calculation, but instead of
1075returning only the final result, :func:`accumulate` returns an iterator that
1076also yields each partial result::
1077
1078    itertools.accumulate([1, 2, 3, 4, 5]) =>
1079      1, 3, 6, 10, 15
1080
1081    itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
1082      1, 2, 6, 24, 120
1083
1084
1085The operator module
1086-------------------
1087
1088The :mod:`operator` module was mentioned earlier.  It contains a set of
1089functions corresponding to Python's operators.  These functions are often useful
1090in functional-style code because they save you from writing trivial functions
1091that perform a single operation.
1092
1093Some of the functions in this module are:
1094
1095* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ...
1096* Logical operations: ``not_()``, ``truth()``.
1097* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1098* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1099* Object identity: ``is_()``, ``is_not()``.
1100
1101Consult the operator module's documentation for a complete list.
1102
1103
1104Small functions and the lambda expression
1105=========================================
1106
1107When writing functional-style programs, you'll often need little functions that
1108act as predicates or that combine elements in some way.
1109
1110If there's a Python built-in or a module function that's suitable, you don't
1111need to define a new function at all::
1112
1113    stripped_lines = [line.strip() for line in lines]
1114    existing_files = filter(os.path.exists, file_list)
1115
1116If the function you need doesn't exist, you need to write it.  One way to write
1117small functions is to use the :keyword:`lambda` expression.  ``lambda`` takes a
1118number of parameters and an expression combining these parameters, and creates
1119an anonymous function that returns the value of the expression::
1120
1121    adder = lambda x, y: x+y
1122
1123    print_assign = lambda name, value: name + '=' + str(value)
1124
1125An alternative is to just use the ``def`` statement and define a function in the
1126usual way::
1127
1128    def adder(x, y):
1129        return x + y
1130
1131    def print_assign(name, value):
1132        return name + '=' + str(value)
1133
1134Which alternative is preferable?  That's a style question; my usual course is to
1135avoid using ``lambda``.
1136
1137One reason for my preference is that ``lambda`` is quite limited in the
1138functions it can define.  The result has to be computable as a single
1139expression, which means you can't have multiway ``if... elif... else``
1140comparisons or ``try... except`` statements.  If you try to do too much in a
1141``lambda`` statement, you'll end up with an overly complicated expression that's
1142hard to read.  Quick, what's the following code doing? ::
1143
1144    import functools
1145    total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
1146
1147You can figure it out, but it takes time to disentangle the expression to figure
1148out what's going on.  Using a short nested ``def`` statements makes things a
1149little bit better::
1150
1151    import functools
1152    def combine(a, b):
1153        return 0, a[1] + b[1]
1154
1155    total = functools.reduce(combine, items)[1]
1156
1157But it would be best of all if I had simply used a ``for`` loop::
1158
1159     total = 0
1160     for a, b in items:
1161         total += b
1162
1163Or the :func:`sum` built-in and a generator expression::
1164
1165     total = sum(b for a, b in items)
1166
1167Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops.
1168
1169Fredrik Lundh once suggested the following set of rules for refactoring uses of
1170``lambda``:
1171
11721. Write a lambda function.
11732. Write a comment explaining what the heck that lambda does.
11743. Study the comment for a while, and think of a name that captures the essence
1175   of the comment.
11764. Convert the lambda to a def statement, using that name.
11775. Remove the comment.
1178
1179I really like these rules, but you're free to disagree
1180about whether this lambda-free style is better.
1181
1182
1183Revision History and Acknowledgements
1184=====================================
1185
1186The author would like to thank the following people for offering suggestions,
1187corrections and assistance with various drafts of this article: Ian Bicking,
1188Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1189Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1190
1191Version 0.1: posted June 30 2006.
1192
1193Version 0.11: posted July 1 2006.  Typo fixes.
1194
1195Version 0.2: posted July 10 2006.  Merged genexp and listcomp sections into one.
1196Typo fixes.
1197
1198Version 0.21: Added more references suggested on the tutor mailing list.
1199
1200Version 0.30: Adds a section on the ``functional`` module written by Collin
1201Winter; adds short section on the operator module; a few other edits.
1202
1203
1204References
1205==========
1206
1207General
1208-------
1209
1210**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1211Gerald Jay Sussman with Julie Sussman.  The book can be found at
1212https://mitpress.mit.edu/sicp.  In this classic textbook of computer science,
1213chapters 2 and 3 discuss the use of sequences and streams to organize the data
1214flow inside a program.  The book uses Scheme for its examples, but many of the
1215design approaches described in these chapters are applicable to functional-style
1216Python code.
1217
1218https://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1219programming that uses Java examples and has a lengthy historical introduction.
1220
1221https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1222describing functional programming.
1223
1224https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1225
1226https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1227
1228Python-specific
1229---------------
1230
1231https://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1232:title-reference:`Text Processing in Python` discusses functional programming
1233for text processing, in the section titled "Utilizing Higher-Order Functions in
1234Text Processing".
1235
1236Mertz also wrote a 3-part series of articles on functional programming
1237for IBM's DeveloperWorks site; see
1238`part 1 <https://developer.ibm.com/articles/l-prog/>`__,
1239`part 2 <https://developer.ibm.com/tutorials/l-prog2/>`__, and
1240`part 3 <https://developer.ibm.com/tutorials/l-prog3/>`__,
1241
1242
1243Python documentation
1244--------------------
1245
1246Documentation for the :mod:`itertools` module.
1247
1248Documentation for the :mod:`functools` module.
1249
1250Documentation for the :mod:`operator` module.
1251
1252:pep:`289`: "Generator Expressions"
1253
1254:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1255features in Python 2.5.
1256
1257.. comment
1258
1259    Handy little function for printing part of an iterator -- used
1260    while writing this document.
1261
1262    import itertools
1263    def print_iter(it):
1264         slice = itertools.islice(it, 10)
1265         for elem in slice[:-1]:
1266             sys.stdout.write(str(elem))
1267             sys.stdout.write(', ')
1268        print(elem[-1])
1269