blob: 07378d1da5da47f75979f5a359a13c8f8bd6ee98 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`itertools` --- Functions creating iterators for efficient looping
2=======================================================================
3
4.. module:: itertools
Raymond Hettinger30c73622010-12-01 23:45:20 +00005 :synopsis: Functions creating iterators for efficient looping.
Georg Brandl116aa622007-08-15 14:28:22 +00006.. moduleauthor:: Raymond Hettinger <python@rcn.com>
7.. sectionauthor:: Raymond Hettinger <python@rcn.com>
8
9
Christian Heimesfe337bf2008-03-23 21:54:12 +000010.. testsetup::
11
Raymond Hettinger30c73622010-12-01 23:45:20 +000012 from itertools import *
Christian Heimesfe337bf2008-03-23 21:54:12 +000013
14
Raymond Hettingerf76b9202009-02-17 20:00:59 +000015This module implements a number of :term:`iterator` building blocks inspired
16by constructs from APL, Haskell, and SML. Each has been recast in a form
17suitable for Python.
Georg Brandl116aa622007-08-15 14:28:22 +000018
19The module standardizes a core set of fast, memory efficient tools that are
Raymond Hettingerf76b9202009-02-17 20:00:59 +000020useful by themselves or in combination. Together, they form an "iterator
21algebra" making it possible to construct specialized tools succinctly and
22efficiently in pure Python.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
Ezio Melottib6605992010-01-21 20:57:24 +000025sequence ``f(0), f(1), ...``. The same effect can be achieved in Python
Raymond Hettingera6c60372008-03-13 01:26:19 +000026by combining :func:`map` and :func:`count` to form ``map(f, count())``.
Georg Brandl116aa622007-08-15 14:28:22 +000027
Raymond Hettinger2c109ab2009-03-12 00:29:44 +000028These tools and their built-in counterparts also work well with the high-speed
29functions in the :mod:`operator` module. For example, the multiplication
30operator can be mapped across two vectors to form an efficient dot-product:
31``sum(map(operator.mul, vector1, vector2))``.
Georg Brandl116aa622007-08-15 14:28:22 +000032
Georg Brandl116aa622007-08-15 14:28:22 +000033
Raymond Hettingerf76b9202009-02-17 20:00:59 +000034**Infinite Iterators:**
Georg Brandl116aa622007-08-15 14:28:22 +000035
Raymond Hettinger5bfd8ce2009-04-10 19:02:36 +000036================== ================= ================================================= =========================================
37Iterator Arguments Results Example
38================== ================= ================================================= =========================================
39:func:`count` start, [step] start, start+step, start+2*step, ... ``count(10) --> 10 11 12 13 14 ...``
40:func:`cycle` p p0, p1, ... plast, p0, p1, ... ``cycle('ABCD') --> A B C D A B C D ...``
41:func:`repeat` elem [,n] elem, elem, elem, ... endlessly or up to n times ``repeat(10, 3) --> 10 10 10``
42================== ================= ================================================= =========================================
Georg Brandl116aa622007-08-15 14:28:22 +000043
Raymond Hettingerf76b9202009-02-17 20:00:59 +000044**Iterators terminating on the shortest input sequence:**
45
Raymond Hettinger5bfd8ce2009-04-10 19:02:36 +000046==================== ============================ ================================================= =============================================================
47Iterator Arguments Results Example
48==================== ============================ ================================================= =============================================================
Raymond Hettinger5d446132011-03-27 18:52:10 -070049:func:`accumulate` p [,func] p0, p0+p1, p0+p1+p2, ... ``accumulate([1,2,3,4,5]) --> 1 3 6 10 15``
Raymond Hettinger5bfd8ce2009-04-10 19:02:36 +000050:func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ``chain('ABC', 'DEF') --> A B C D E F``
51:func:`compress` data, selectors (d[0] if s[0]), (d[1] if s[1]), ... ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F``
52:func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1``
Georg Brandlc2da5ce2009-08-13 09:16:39 +000053:func:`filterfalse` pred, seq elements of seq where pred(elem) is False ``filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8``
Raymond Hettinger5bfd8ce2009-04-10 19:02:36 +000054:func:`groupby` iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v)
55:func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ``islice('ABCDEFG', 2, None) --> C D E F G``
56:func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000``
57:func:`takewhile` pred, seq seq[0], seq[1], until pred fails ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4``
58:func:`tee` it, n it1, it2 , ... itn splits one iterator into n
Georg Brandlc2da5ce2009-08-13 09:16:39 +000059:func:`zip_longest` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ``zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-``
Raymond Hettinger5bfd8ce2009-04-10 19:02:36 +000060==================== ============================ ================================================= =============================================================
Raymond Hettingerf76b9202009-02-17 20:00:59 +000061
62**Combinatoric generators:**
63
Raymond Hettinger7f587cd2009-04-10 19:43:50 +000064============================================== ==================== =============================================================
65Iterator Arguments Results
66============================================== ==================== =============================================================
67:func:`product` p, q, ... [repeat=1] cartesian product, equivalent to a nested for-loop
68:func:`permutations` p[, r] r-length tuples, all possible orderings, no repeated elements
Raymond Hettinger36c3c022009-11-19 01:20:07 +000069:func:`combinations` p, r r-length tuples, in sorted order, no repeated elements
70:func:`combinations_with_replacement` p, r r-length tuples, in sorted order, with repeated elements
Raymond Hettinger7f587cd2009-04-10 19:43:50 +000071``product('ABCD', repeat=2)`` ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD``
72``permutations('ABCD', 2)`` ``AB AC AD BA BC BD CA CB CD DA DB DC``
73``combinations('ABCD', 2)`` ``AB AC AD BC BD CD``
74``combinations_with_replacement('ABCD', 2)`` ``AA AB AC AD BB BC BD CC CD DD``
75============================================== ==================== =============================================================
Georg Brandl116aa622007-08-15 14:28:22 +000076
77
78.. _itertools-functions:
79
80Itertool functions
81------------------
82
83The following module functions all construct and return iterators. Some provide
84streams of infinite length, so they should only be accessed by functions or
85loops that truncate the stream.
86
Raymond Hettinger5d446132011-03-27 18:52:10 -070087.. function:: accumulate(iterable[, func])
Raymond Hettingeradb81462010-12-01 22:50:36 +000088
Raymond Hettinger2d93e6e2010-12-03 02:33:53 +000089 Make an iterator that returns accumulated sums. Elements may be any addable
Raymond Hettinger5d446132011-03-27 18:52:10 -070090 type including :class:`Decimal` or :class:`Fraction`. If the optional
91 *func* argument is supplied, it should be a function of two arguments
92 and it will be used instead of addition.
Raymond Hettingeradb81462010-12-01 22:50:36 +000093
Raymond Hettinger5d446132011-03-27 18:52:10 -070094 Equivalent to::
95
96 def accumulate(iterable, func=operator.add):
Raymond Hettingeradb81462010-12-01 22:50:36 +000097 'Return running totals'
Raymond Hettingerd8ff4652010-12-03 02:09:34 +000098 # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
Raymond Hettinger5d446132011-03-27 18:52:10 -070099 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000100 it = iter(iterable)
101 total = next(it)
102 yield total
103 for element in it:
Raymond Hettinger5d446132011-03-27 18:52:10 -0700104 total = func(total, element)
Raymond Hettingerd8ff4652010-12-03 02:09:34 +0000105 yield total
Raymond Hettingeradb81462010-12-01 22:50:36 +0000106
Raymond Hettinger5d446132011-03-27 18:52:10 -0700107 Uses for the *func* argument include :func:`min` for a running minimum,
108 :func:`max` for a running maximum, and :func:`operator.mul` for a running
109 product::
110
111 >>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
112 >>> list(accumulate(data, operator.mul)) # running product
113 [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
114 >>> list(accumulate(data, max)) # running maximum
115 [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
116
117 # Amortize a 5% loan of 1000 with 4 annual payments of 90
118 >>> cashflows = [1000, -90, -90, -90, -90]
119 >>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
120 [1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
121
Raymond Hettingeradb81462010-12-01 22:50:36 +0000122 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Raymond Hettinger5d446132011-03-27 18:52:10 -0700124 .. versionchanged:: 3.3
125 Added the optional *func* parameter.
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127.. function:: chain(*iterables)
128
Raymond Hettinger30c73622010-12-01 23:45:20 +0000129 Make an iterator that returns elements from the first iterable until it is
130 exhausted, then proceeds to the next iterable, until all of the iterables are
131 exhausted. Used for treating consecutive sequences as a single sequence.
132 Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Raymond Hettinger30c73622010-12-01 23:45:20 +0000134 def chain(*iterables):
135 # chain('ABC', 'DEF') --> A B C D E F
136 for it in iterables:
137 for element in it:
138 yield element
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
Georg Brandl933b9742010-07-29 14:36:11 +0000141.. classmethod:: chain.from_iterable(iterable)
Christian Heimes70e7ea22008-02-28 20:02:27 +0000142
Raymond Hettinger30c73622010-12-01 23:45:20 +0000143 Alternate constructor for :func:`chain`. Gets chained inputs from a
144 single iterable argument that is evaluated lazily. Equivalent to::
Christian Heimes70e7ea22008-02-28 20:02:27 +0000145
Raymond Hettinger30c73622010-12-01 23:45:20 +0000146 @classmethod
147 def from_iterable(iterables):
148 # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
149 for it in iterables:
150 for element in it:
151 yield element
Christian Heimes70e7ea22008-02-28 20:02:27 +0000152
Christian Heimes78644762008-03-04 23:39:23 +0000153
Christian Heimes836baa52008-02-26 08:18:30 +0000154.. function:: combinations(iterable, r)
155
Raymond Hettinger30c73622010-12-01 23:45:20 +0000156 Return *r* length subsequences of elements from the input *iterable*.
Christian Heimes836baa52008-02-26 08:18:30 +0000157
Raymond Hettinger30c73622010-12-01 23:45:20 +0000158 Combinations are emitted in lexicographic sort order. So, if the
159 input *iterable* is sorted, the combination tuples will be produced
160 in sorted order.
Christian Heimes836baa52008-02-26 08:18:30 +0000161
Raymond Hettinger30c73622010-12-01 23:45:20 +0000162 Elements are treated as unique based on their position, not on their
163 value. So if the input elements are unique, there will be no repeat
164 values in each combination.
Christian Heimes836baa52008-02-26 08:18:30 +0000165
Raymond Hettinger30c73622010-12-01 23:45:20 +0000166 Equivalent to::
Christian Heimes836baa52008-02-26 08:18:30 +0000167
168 def combinations(iterable, r):
Raymond Hettingerdd1150e2008-03-13 02:39:40 +0000169 # combinations('ABCD', 2) --> AB AC AD BC BD CD
170 # combinations(range(4), 3) --> 012 013 023 123
Christian Heimes836baa52008-02-26 08:18:30 +0000171 pool = tuple(iterable)
Christian Heimes380f7f22008-02-28 11:19:05 +0000172 n = len(pool)
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000173 if r > n:
174 return
175 indices = list(range(r))
Christian Heimesb558a2e2008-03-02 22:46:37 +0000176 yield tuple(pool[i] for i in indices)
Raymond Hettingercf984ce2009-02-18 20:56:51 +0000177 while True:
Christian Heimes380f7f22008-02-28 11:19:05 +0000178 for i in reversed(range(r)):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000179 if indices[i] != i + n - r:
Christian Heimes836baa52008-02-26 08:18:30 +0000180 break
Christian Heimes380f7f22008-02-28 11:19:05 +0000181 else:
182 return
Christian Heimesb558a2e2008-03-02 22:46:37 +0000183 indices[i] += 1
Christian Heimes380f7f22008-02-28 11:19:05 +0000184 for j in range(i+1, r):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000185 indices[j] = indices[j-1] + 1
186 yield tuple(pool[i] for i in indices)
Christian Heimes836baa52008-02-26 08:18:30 +0000187
Raymond Hettinger30c73622010-12-01 23:45:20 +0000188 The code for :func:`combinations` can be also expressed as a subsequence
189 of :func:`permutations` after filtering entries where the elements are not
190 in sorted order (according to their position in the input pool)::
Christian Heimes78644762008-03-04 23:39:23 +0000191
192 def combinations(iterable, r):
193 pool = tuple(iterable)
194 n = len(pool)
195 for indices in permutations(range(n), r):
196 if sorted(indices) == list(indices):
197 yield tuple(pool[i] for i in indices)
198
Raymond Hettinger30c73622010-12-01 23:45:20 +0000199 The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n``
200 or zero when ``r > n``.
Christian Heimes836baa52008-02-26 08:18:30 +0000201
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000202.. function:: combinations_with_replacement(iterable, r)
203
Raymond Hettinger30c73622010-12-01 23:45:20 +0000204 Return *r* length subsequences of elements from the input *iterable*
205 allowing individual elements to be repeated more than once.
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000206
Raymond Hettinger30c73622010-12-01 23:45:20 +0000207 Combinations are emitted in lexicographic sort order. So, if the
208 input *iterable* is sorted, the combination tuples will be produced
209 in sorted order.
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000210
Raymond Hettinger30c73622010-12-01 23:45:20 +0000211 Elements are treated as unique based on their position, not on their
212 value. So if the input elements are unique, the generated combinations
213 will also be unique.
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000214
Raymond Hettinger30c73622010-12-01 23:45:20 +0000215 Equivalent to::
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000216
217 def combinations_with_replacement(iterable, r):
218 # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
219 pool = tuple(iterable)
220 n = len(pool)
221 if not n and r:
222 return
223 indices = [0] * r
224 yield tuple(pool[i] for i in indices)
Raymond Hettingercf984ce2009-02-18 20:56:51 +0000225 while True:
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000226 for i in reversed(range(r)):
227 if indices[i] != n - 1:
228 break
229 else:
230 return
231 indices[i:] = [indices[i] + 1] * (r - i)
232 yield tuple(pool[i] for i in indices)
233
Raymond Hettinger30c73622010-12-01 23:45:20 +0000234 The code for :func:`combinations_with_replacement` can be also expressed as
235 a subsequence of :func:`product` after filtering entries where the elements
236 are not in sorted order (according to their position in the input pool)::
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000237
238 def combinations_with_replacement(iterable, r):
239 pool = tuple(iterable)
240 n = len(pool)
241 for indices in product(range(n), repeat=r):
242 if sorted(indices) == list(indices):
243 yield tuple(pool[i] for i in indices)
244
Raymond Hettinger30c73622010-12-01 23:45:20 +0000245 The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``.
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000246
Raymond Hettinger30c73622010-12-01 23:45:20 +0000247 .. versionadded:: 3.1
Raymond Hettingerd07d9392009-01-27 04:20:44 +0000248
Georg Brandl67b21b72010-08-17 15:07:14 +0000249
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000250.. function:: compress(data, selectors)
251
Raymond Hettinger30c73622010-12-01 23:45:20 +0000252 Make an iterator that filters elements from *data* returning only those that
253 have a corresponding element in *selectors* that evaluates to ``True``.
254 Stops when either the *data* or *selectors* iterables has been exhausted.
255 Equivalent to::
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000256
Raymond Hettinger30c73622010-12-01 23:45:20 +0000257 def compress(data, selectors):
258 # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
259 return (d for d, s in zip(data, selectors) if s)
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000260
Raymond Hettinger30c73622010-12-01 23:45:20 +0000261 .. versionadded:: 3.1
Raymond Hettinger6b3b0fc2009-01-26 02:56:58 +0000262
263
Raymond Hettinger9e8dbbc2009-02-14 04:21:49 +0000264.. function:: count(start=0, step=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000265
Raymond Hettinger30c73622010-12-01 23:45:20 +0000266 Make an iterator that returns evenly spaced values starting with *n*. Often
267 used as an argument to :func:`map` to generate consecutive data points.
268 Also, used with :func:`zip` to add sequence numbers. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Raymond Hettinger30c73622010-12-01 23:45:20 +0000270 def count(start=0, step=1):
271 # count(10) --> 10 11 12 13 14 ...
Georg Brandl37a80dc2011-01-13 07:31:18 +0000272 # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
Raymond Hettinger30c73622010-12-01 23:45:20 +0000273 n = start
274 while True:
275 yield n
276 n += step
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Raymond Hettinger30c73622010-12-01 23:45:20 +0000278 When counting with floating point numbers, better accuracy can sometimes be
279 achieved by substituting multiplicative code such as: ``(start + step * i
280 for i in count())``.
Raymond Hettinger5bc472a2009-06-17 01:40:52 +0000281
Raymond Hettinger30c73622010-12-01 23:45:20 +0000282 .. versionchanged:: 3.1
283 Added *step* argument and allowed non-integer arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285.. function:: cycle(iterable)
286
Raymond Hettinger30c73622010-12-01 23:45:20 +0000287 Make an iterator returning elements from the iterable and saving a copy of each.
288 When the iterable is exhausted, return elements from the saved copy. Repeats
289 indefinitely. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Raymond Hettinger30c73622010-12-01 23:45:20 +0000291 def cycle(iterable):
292 # cycle('ABCD') --> A B C D A B C D A B C D ...
293 saved = []
294 for element in iterable:
295 yield element
296 saved.append(element)
297 while saved:
298 for element in saved:
Georg Brandl116aa622007-08-15 14:28:22 +0000299 yield element
300
Raymond Hettinger30c73622010-12-01 23:45:20 +0000301 Note, this member of the toolkit may require significant auxiliary storage
302 (depending on the length of the iterable).
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304
305.. function:: dropwhile(predicate, iterable)
306
Raymond Hettinger30c73622010-12-01 23:45:20 +0000307 Make an iterator that drops elements from the iterable as long as the predicate
308 is true; afterwards, returns every element. Note, the iterator does not produce
309 *any* output until the predicate first becomes false, so it may have a lengthy
310 start-up time. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Raymond Hettinger30c73622010-12-01 23:45:20 +0000312 def dropwhile(predicate, iterable):
313 # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
314 iterable = iter(iterable)
315 for x in iterable:
316 if not predicate(x):
317 yield x
318 break
319 for x in iterable:
320 yield x
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Raymond Hettinger749761e2009-01-27 04:42:48 +0000322.. function:: filterfalse(predicate, iterable)
323
Raymond Hettinger30c73622010-12-01 23:45:20 +0000324 Make an iterator that filters elements from iterable returning only those for
325 which the predicate is ``False``. If *predicate* is ``None``, return the items
326 that are false. Equivalent to::
Raymond Hettinger749761e2009-01-27 04:42:48 +0000327
Raymond Hettinger30c73622010-12-01 23:45:20 +0000328 def filterfalse(predicate, iterable):
329 # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
330 if predicate is None:
331 predicate = bool
332 for x in iterable:
333 if not predicate(x):
334 yield x
Raymond Hettinger749761e2009-01-27 04:42:48 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Georg Brandl3dd33882009-06-01 17:35:27 +0000337.. function:: groupby(iterable, key=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Raymond Hettinger30c73622010-12-01 23:45:20 +0000339 Make an iterator that returns consecutive keys and groups from the *iterable*.
340 The *key* is a function computing a key value for each element. If not
341 specified or is ``None``, *key* defaults to an identity function and returns
342 the element unchanged. Generally, the iterable needs to already be sorted on
343 the same key function.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Raymond Hettinger30c73622010-12-01 23:45:20 +0000345 The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix. It
346 generates a break or new group every time the value of the key function changes
347 (which is why it is usually necessary to have sorted the data using the same key
348 function). That behavior differs from SQL's GROUP BY which aggregates common
349 elements regardless of their input order.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Raymond Hettinger30c73622010-12-01 23:45:20 +0000351 The returned group is itself an iterator that shares the underlying iterable
352 with :func:`groupby`. Because the source is shared, when the :func:`groupby`
353 object is advanced, the previous group is no longer visible. So, if that data
354 is needed later, it should be stored as a list::
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Raymond Hettinger30c73622010-12-01 23:45:20 +0000356 groups = []
357 uniquekeys = []
358 data = sorted(data, key=keyfunc)
359 for k, g in groupby(data, keyfunc):
360 groups.append(list(g)) # Store group iterator as a list
361 uniquekeys.append(k)
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Raymond Hettinger30c73622010-12-01 23:45:20 +0000363 :func:`groupby` is equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Raymond Hettinger30c73622010-12-01 23:45:20 +0000365 class groupby:
366 # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
367 # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
368 def __init__(self, iterable, key=None):
369 if key is None:
370 key = lambda x: x
371 self.keyfunc = key
372 self.it = iter(iterable)
373 self.tgtkey = self.currkey = self.currvalue = object()
374 def __iter__(self):
375 return self
376 def __next__(self):
377 while self.currkey == self.tgtkey:
378 self.currvalue = next(self.it) # Exit on StopIteration
379 self.currkey = self.keyfunc(self.currvalue)
380 self.tgtkey = self.currkey
381 return (self.currkey, self._grouper(self.tgtkey))
382 def _grouper(self, tgtkey):
383 while self.currkey == tgtkey:
384 yield self.currvalue
385 self.currvalue = next(self.it) # Exit on StopIteration
386 self.currkey = self.keyfunc(self.currvalue)
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Georg Brandl116aa622007-08-15 14:28:22 +0000389.. function:: islice(iterable, [start,] stop [, step])
390
Raymond Hettinger30c73622010-12-01 23:45:20 +0000391 Make an iterator that returns selected elements from the iterable. If *start* is
392 non-zero, then elements from the iterable are skipped until start is reached.
393 Afterward, elements are returned consecutively unless *step* is set higher than
394 one which results in items being skipped. If *stop* is ``None``, then iteration
395 continues until the iterator is exhausted, if at all; otherwise, it stops at the
396 specified position. Unlike regular slicing, :func:`islice` does not support
397 negative values for *start*, *stop*, or *step*. Can be used to extract related
398 fields from data where the internal structure has been flattened (for example, a
399 multi-line report may list a name field on every third line). Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Raymond Hettinger30c73622010-12-01 23:45:20 +0000401 def islice(iterable, *args):
402 # islice('ABCDEFG', 2) --> A B
403 # islice('ABCDEFG', 2, 4) --> C D
404 # islice('ABCDEFG', 2, None) --> C D E F G
405 # islice('ABCDEFG', 0, None, 2) --> A C E G
406 s = slice(*args)
407 it = iter(range(s.start or 0, s.stop or sys.maxsize, s.step or 1))
408 nexti = next(it)
409 for i, element in enumerate(iterable):
410 if i == nexti:
411 yield element
412 nexti = next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Raymond Hettinger30c73622010-12-01 23:45:20 +0000414 If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
415 then the step defaults to one.
Georg Brandl116aa622007-08-15 14:28:22 +0000416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Georg Brandl3dd33882009-06-01 17:35:27 +0000418.. function:: permutations(iterable, r=None)
Christian Heimes70e7ea22008-02-28 20:02:27 +0000419
Raymond Hettinger30c73622010-12-01 23:45:20 +0000420 Return successive *r* length permutations of elements in the *iterable*.
Christian Heimes70e7ea22008-02-28 20:02:27 +0000421
Raymond Hettinger30c73622010-12-01 23:45:20 +0000422 If *r* is not specified or is ``None``, then *r* defaults to the length
423 of the *iterable* and all possible full-length permutations
424 are generated.
Christian Heimes70e7ea22008-02-28 20:02:27 +0000425
Raymond Hettinger30c73622010-12-01 23:45:20 +0000426 Permutations are emitted in lexicographic sort order. So, if the
427 input *iterable* is sorted, the permutation tuples will be produced
428 in sorted order.
Christian Heimes70e7ea22008-02-28 20:02:27 +0000429
Raymond Hettinger30c73622010-12-01 23:45:20 +0000430 Elements are treated as unique based on their position, not on their
431 value. So if the input elements are unique, there will be no repeat
432 values in each permutation.
Christian Heimes70e7ea22008-02-28 20:02:27 +0000433
Raymond Hettinger30c73622010-12-01 23:45:20 +0000434 Equivalent to::
Christian Heimesb558a2e2008-03-02 22:46:37 +0000435
436 def permutations(iterable, r=None):
Raymond Hettingerdd1150e2008-03-13 02:39:40 +0000437 # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
438 # permutations(range(3)) --> 012 021 102 120 201 210
Christian Heimesb558a2e2008-03-02 22:46:37 +0000439 pool = tuple(iterable)
440 n = len(pool)
441 r = n if r is None else r
Raymond Hettinger5bad41e2009-01-08 21:01:54 +0000442 if r > n:
443 return
444 indices = list(range(n))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000445 cycles = range(n, n-r, -1)
Christian Heimesb558a2e2008-03-02 22:46:37 +0000446 yield tuple(pool[i] for i in indices[:r])
447 while n:
448 for i in reversed(range(r)):
449 cycles[i] -= 1
450 if cycles[i] == 0:
451 indices[i:] = indices[i+1:] + indices[i:i+1]
452 cycles[i] = n - i
453 else:
454 j = cycles[i]
455 indices[i], indices[-j] = indices[-j], indices[i]
456 yield tuple(pool[i] for i in indices[:r])
457 break
458 else:
459 return
Christian Heimes70e7ea22008-02-28 20:02:27 +0000460
Raymond Hettinger30c73622010-12-01 23:45:20 +0000461 The code for :func:`permutations` can be also expressed as a subsequence of
462 :func:`product`, filtered to exclude entries with repeated elements (those
463 from the same position in the input pool)::
Christian Heimes78644762008-03-04 23:39:23 +0000464
465 def permutations(iterable, r=None):
466 pool = tuple(iterable)
467 n = len(pool)
468 r = n if r is None else r
469 for indices in product(range(n), repeat=r):
470 if len(set(indices)) == r:
471 yield tuple(pool[i] for i in indices)
472
Raymond Hettinger30c73622010-12-01 23:45:20 +0000473 The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n``
474 or zero when ``r > n``.
Christian Heimes70e7ea22008-02-28 20:02:27 +0000475
Georg Brandl3dd33882009-06-01 17:35:27 +0000476.. function:: product(*iterables, repeat=1)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000477
Raymond Hettinger30c73622010-12-01 23:45:20 +0000478 Cartesian product of input iterables.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000479
Raymond Hettinger30c73622010-12-01 23:45:20 +0000480 Equivalent to nested for-loops in a generator expression. For example,
481 ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000482
Raymond Hettinger30c73622010-12-01 23:45:20 +0000483 The nested loops cycle like an odometer with the rightmost element advancing
484 on every iteration. This pattern creates a lexicographic ordering so that if
485 the input's iterables are sorted, the product tuples are emitted in sorted
486 order.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000487
Raymond Hettinger30c73622010-12-01 23:45:20 +0000488 To compute the product of an iterable with itself, specify the number of
489 repetitions with the optional *repeat* keyword argument. For example,
490 ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000491
Raymond Hettinger30c73622010-12-01 23:45:20 +0000492 This function is equivalent to the following code, except that the
493 actual implementation does not build up intermediate results in memory::
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000494
Raymond Hettinger30c73622010-12-01 23:45:20 +0000495 def product(*args, repeat=1):
496 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
497 # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
498 pools = [tuple(pool) for pool in args] * repeat
499 result = [[]]
500 for pool in pools:
501 result = [x+[y] for x in result for y in pool]
502 for prod in result:
503 yield tuple(prod)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000504
505
Raymond Hettingerd75ad442009-06-01 19:16:52 +0000506.. function:: repeat(object[, times])
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Raymond Hettinger30c73622010-12-01 23:45:20 +0000508 Make an iterator that returns *object* over and over again. Runs indefinitely
509 unless the *times* argument is specified. Used as argument to :func:`map` for
510 invariant parameters to the called function. Also used with :func:`zip` to
511 create an invariant part of a tuple record. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000512
Raymond Hettinger30c73622010-12-01 23:45:20 +0000513 def repeat(object, times=None):
514 # repeat(10, 3) --> 10 10 10
515 if times is None:
516 while True:
517 yield object
518 else:
519 for i in range(times):
520 yield object
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
523.. function:: starmap(function, iterable)
524
Raymond Hettinger30c73622010-12-01 23:45:20 +0000525 Make an iterator that computes the function using arguments obtained from
526 the iterable. Used instead of :func:`map` when argument parameters are already
527 grouped in tuples from a single iterable (the data has been "pre-zipped"). The
528 difference between :func:`map` and :func:`starmap` parallels the distinction
529 between ``function(a,b)`` and ``function(*c)``. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Raymond Hettinger30c73622010-12-01 23:45:20 +0000531 def starmap(function, iterable):
532 # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
533 for args in iterable:
534 yield function(*args)
Christian Heimes679db4a2008-01-18 09:56:22 +0000535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537.. function:: takewhile(predicate, iterable)
538
Raymond Hettinger30c73622010-12-01 23:45:20 +0000539 Make an iterator that returns elements from the iterable as long as the
540 predicate is true. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000541
Raymond Hettinger30c73622010-12-01 23:45:20 +0000542 def takewhile(predicate, iterable):
543 # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
544 for x in iterable:
545 if predicate(x):
546 yield x
547 else:
548 break
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550
Georg Brandl3dd33882009-06-01 17:35:27 +0000551.. function:: tee(iterable, n=2)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Raymond Hettinger30c73622010-12-01 23:45:20 +0000553 Return *n* independent iterators from a single iterable. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Raymond Hettingercf984ce2009-02-18 20:56:51 +0000555 def tee(iterable, n=2):
556 it = iter(iterable)
557 deques = [collections.deque() for i in range(n)]
558 def gen(mydeque):
559 while True:
560 if not mydeque: # when the local deque is empty
561 newval = next(it) # fetch a new value and
562 for d in deques: # load it to all the deques
563 d.append(newval)
564 yield mydeque.popleft()
565 return tuple(gen(d) for d in deques)
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Raymond Hettinger30c73622010-12-01 23:45:20 +0000567 Once :func:`tee` has made a split, the original *iterable* should not be
568 used anywhere else; otherwise, the *iterable* could get advanced without
569 the tee objects being informed.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Raymond Hettinger30c73622010-12-01 23:45:20 +0000571 This itertool may require significant auxiliary storage (depending on how
572 much temporary data needs to be stored). In general, if one iterator uses
573 most or all of the data before another iterator starts, it is faster to use
574 :func:`list` instead of :func:`tee`.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Georg Brandl3dd33882009-06-01 17:35:27 +0000577.. function:: zip_longest(*iterables, fillvalue=None)
Raymond Hettinger749761e2009-01-27 04:42:48 +0000578
Raymond Hettinger30c73622010-12-01 23:45:20 +0000579 Make an iterator that aggregates elements from each of the iterables. If the
580 iterables are of uneven length, missing values are filled-in with *fillvalue*.
581 Iteration continues until the longest iterable is exhausted. Equivalent to::
Raymond Hettinger749761e2009-01-27 04:42:48 +0000582
Raymond Hettinger30c73622010-12-01 23:45:20 +0000583 def zip_longest(*args, fillvalue=None):
584 # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
585 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
586 yield counter() # yields the fillvalue, or raises IndexError
587 fillers = repeat(fillvalue)
588 iters = [chain(it, sentinel(), fillers) for it in args]
589 try:
590 for tup in zip(*iters):
591 yield tup
592 except IndexError:
593 pass
Raymond Hettinger749761e2009-01-27 04:42:48 +0000594
Raymond Hettinger30c73622010-12-01 23:45:20 +0000595 If one of the iterables is potentially infinite, then the :func:`zip_longest`
596 function should be wrapped with something that limits the number of calls
597 (for example :func:`islice` or :func:`takewhile`). If not specified,
598 *fillvalue* defaults to ``None``.
Raymond Hettinger749761e2009-01-27 04:42:48 +0000599
600
Georg Brandl116aa622007-08-15 14:28:22 +0000601.. _itertools-recipes:
602
Raymond Hettinger1fa76822010-12-06 23:31:36 +0000603Itertools Recipes
604-----------------
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606This section shows recipes for creating an extended toolset using the existing
607itertools as building blocks.
608
609The extended tools offer the same high performance as the underlying toolset.
610The superior memory performance is kept by processing elements one at a time
611rather than bringing the whole iterable into memory all at once. Code volume is
612kept small by linking the tools together in a functional style which helps
613eliminate temporary variables. High speed is retained by preferring
Georg Brandl9afde1c2007-11-01 20:32:30 +0000614"vectorized" building blocks over the use of for-loops and :term:`generator`\s
Christian Heimesfe337bf2008-03-23 21:54:12 +0000615which incur interpreter overhead.
616
617.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Raymond Hettinger30c73622010-12-01 23:45:20 +0000619 def take(n, iterable):
620 "Return first n items of the iterable as a list"
621 return list(islice(iterable, n))
Georg Brandl116aa622007-08-15 14:28:22 +0000622
Raymond Hettinger30c73622010-12-01 23:45:20 +0000623 def tabulate(function, start=0):
624 "Return function(0), function(1), ..."
625 return map(function, count(start))
Raymond Hettingerdd1150e2008-03-13 02:39:40 +0000626
Raymond Hettinger30c73622010-12-01 23:45:20 +0000627 def consume(iterator, n):
628 "Advance the iterator n-steps ahead. If n is none, consume entirely."
629 # Use functions that consume iterators at C speed.
630 if n is None:
631 # feed the entire iterator into a zero-length deque
632 collections.deque(iterator, maxlen=0)
633 else:
634 # advance to the empty slice starting at position n
635 next(islice(iterator, n, n), None)
Raymond Hettingerfa007962009-03-09 11:55:25 +0000636
Raymond Hettinger30c73622010-12-01 23:45:20 +0000637 def nth(iterable, n, default=None):
638 "Returns the nth item or a default value"
639 return next(islice(iterable, n, None), default)
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Raymond Hettinger30c73622010-12-01 23:45:20 +0000641 def quantify(iterable, pred=bool):
642 "Count how many times the predicate is true"
643 return sum(map(pred, iterable))
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Raymond Hettinger30c73622010-12-01 23:45:20 +0000645 def padnone(iterable):
646 """Returns the sequence elements and then returns None indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +0000647
Raymond Hettinger30c73622010-12-01 23:45:20 +0000648 Useful for emulating the behavior of the built-in map() function.
649 """
650 return chain(iterable, repeat(None))
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Raymond Hettinger30c73622010-12-01 23:45:20 +0000652 def ncycles(iterable, n):
653 "Returns the sequence elements n times"
654 return chain.from_iterable(repeat(tuple(iterable), n))
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Raymond Hettinger30c73622010-12-01 23:45:20 +0000656 def dotproduct(vec1, vec2):
657 return sum(map(operator.mul, vec1, vec2))
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Raymond Hettinger30c73622010-12-01 23:45:20 +0000659 def flatten(listOfLists):
660 "Flatten one level of nesting"
661 return chain.from_iterable(listOfLists)
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Raymond Hettinger30c73622010-12-01 23:45:20 +0000663 def repeatfunc(func, times=None, *args):
664 """Repeat calls to func with specified arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Raymond Hettinger30c73622010-12-01 23:45:20 +0000666 Example: repeatfunc(random.random)
667 """
668 if times is None:
669 return starmap(func, repeat(args))
670 return starmap(func, repeat(args, times))
Georg Brandl116aa622007-08-15 14:28:22 +0000671
Raymond Hettinger30c73622010-12-01 23:45:20 +0000672 def pairwise(iterable):
673 "s -> (s0,s1), (s1,s2), (s2, s3), ..."
674 a, b = tee(iterable)
675 next(b, None)
676 return zip(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Raymond Hettinger30c73622010-12-01 23:45:20 +0000678 def grouper(n, iterable, fillvalue=None):
679 "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
680 args = [iter(iterable)] * n
681 return zip_longest(*args, fillvalue=fillvalue)
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Raymond Hettinger30c73622010-12-01 23:45:20 +0000683 def roundrobin(*iterables):
684 "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
685 # Recipe credited to George Sakkis
686 pending = len(iterables)
687 nexts = cycle(iter(it).__next__ for it in iterables)
688 while pending:
689 try:
690 for next in nexts:
691 yield next()
692 except StopIteration:
693 pending -= 1
694 nexts = cycle(islice(nexts, pending))
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Raymond Hettinger30c73622010-12-01 23:45:20 +0000696 def partition(pred, iterable):
697 'Use a predicate to partition entries into false entries and true entries'
698 # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
699 t1, t2 = tee(iterable)
700 return filterfalse(pred, t1), filter(pred, t2)
Raymond Hettinger5ce0aa22010-12-01 10:49:19 +0000701
Raymond Hettinger30c73622010-12-01 23:45:20 +0000702 def powerset(iterable):
703 "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
704 s = list(iterable)
705 return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Raymond Hettinger08d01ee2010-08-07 05:36:53 +0000706
Raymond Hettinger30c73622010-12-01 23:45:20 +0000707 def unique_everseen(iterable, key=None):
708 "List unique elements, preserving order. Remember all elements ever seen."
709 # unique_everseen('AAAABBBCCDAABBB') --> A B C D
710 # unique_everseen('ABBCcAD', str.lower) --> A B C D
711 seen = set()
712 seen_add = seen.add
713 if key is None:
714 for element in filterfalse(seen.__contains__, iterable):
715 seen_add(element)
716 yield element
717 else:
718 for element in iterable:
719 k = key(element)
720 if k not in seen:
721 seen_add(k)
722 yield element
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000723
Raymond Hettinger30c73622010-12-01 23:45:20 +0000724 def unique_justseen(iterable, key=None):
725 "List unique elements, preserving order. Remember only the element just seen."
726 # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
727 # unique_justseen('ABBCcAD', str.lower) --> A B C A D
728 return map(next, map(itemgetter(1), groupby(iterable, key)))
Raymond Hettingerad9d96b2009-01-02 21:39:07 +0000729
Raymond Hettinger30c73622010-12-01 23:45:20 +0000730 def iter_except(func, exception, first=None):
731 """ Call a function repeatedly until an exception is raised.
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000732
Raymond Hettinger30c73622010-12-01 23:45:20 +0000733 Converts a call-until-exception interface to an iterator interface.
734 Like __builtin__.iter(func, sentinel) but uses an exception instead
735 of a sentinel to end the loop.
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000736
Raymond Hettinger30c73622010-12-01 23:45:20 +0000737 Examples:
738 iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator
739 iter_except(d.popitem, KeyError) # non-blocking dict iterator
740 iter_except(d.popleft, IndexError) # non-blocking deque iterator
741 iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue
742 iter_except(s.pop, KeyError) # non-blocking set iterator
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000743
Raymond Hettinger30c73622010-12-01 23:45:20 +0000744 """
745 try:
746 if first is not None:
747 yield first() # For database APIs needing an initial cast to db.first()
748 while 1:
749 yield func()
750 except exception:
751 pass
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000752
Raymond Hettinger30c73622010-12-01 23:45:20 +0000753 def random_product(*args, repeat=1):
754 "Random selection from itertools.product(*args, **kwds)"
755 pools = [tuple(pool) for pool in args] * repeat
756 return tuple(random.choice(pool) for pool in pools)
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000757
Raymond Hettinger30c73622010-12-01 23:45:20 +0000758 def random_permutation(iterable, r=None):
759 "Random selection from itertools.permutations(iterable, r)"
760 pool = tuple(iterable)
761 r = len(pool) if r is None else r
762 return tuple(random.sample(pool, r))
Raymond Hettinger063a4b62010-04-02 04:18:18 +0000763
Raymond Hettinger30c73622010-12-01 23:45:20 +0000764 def random_combination(iterable, r):
765 "Random selection from itertools.combinations(iterable, r)"
766 pool = tuple(iterable)
767 n = len(pool)
768 indices = sorted(random.sample(range(n), r))
769 return tuple(pool[i] for i in indices)
Raymond Hettinger063a4b62010-04-02 04:18:18 +0000770
Raymond Hettinger30c73622010-12-01 23:45:20 +0000771 def random_combination_with_replacement(iterable, r):
772 "Random selection from itertools.combinations_with_replacement(iterable, r)"
773 pool = tuple(iterable)
774 n = len(pool)
775 indices = sorted(random.randrange(n) for i in range(r))
776 return tuple(pool[i] for i in indices)
Raymond Hettinger063a4b62010-04-02 04:18:18 +0000777
Raymond Hettingerfc91aa22010-03-28 18:27:13 +0000778Note, many of the above recipes can be optimized by replacing global lookups
779with local variables defined as default values. For example, the
780*dotproduct* recipe can be written as::
781
Raymond Hettinger30c73622010-12-01 23:45:20 +0000782 def dotproduct(vec1, vec2, sum=sum, map=map, mul=operator.mul):
783 return sum(map(mul, vec1, vec2))