diff options
author | Lisa Roach <lisaroach14@gmail.com> | 2018-09-24 00:34:59 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-09-24 00:34:59 (GMT) |
commit | 9718b59ee5f2416cdb8116ea5837b062faf0d9f8 (patch) | |
tree | 4cb5ba002be73a33680252e355c13800f4e9c42c /Doc | |
parent | c87d9f406bb23657c1b4cd63017bb7bd7693a1fb (diff) | |
download | cpython-9718b59ee5f2416cdb8116ea5837b062faf0d9f8.zip cpython-9718b59ee5f2416cdb8116ea5837b062faf0d9f8.tar.gz cpython-9718b59ee5f2416cdb8116ea5837b062faf0d9f8.tar.bz2 |
bpo-34659: Adds initial kwarg to itertools.accumulate() (GH-9345)
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/itertools.rst | 30 |
1 files changed, 21 insertions, 9 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 959424f..b1513cd 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -86,29 +86,38 @@ The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream. -.. function:: accumulate(iterable[, func]) +.. function:: accumulate(iterable[, func, *, initial=None]) Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional - *func* argument). If *func* is supplied, it should be a function + *func* argument). + + If *func* is supplied, it should be a function of two arguments. Elements of the input *iterable* may be any type that can be accepted as arguments to *func*. (For example, with the default operation of addition, elements may be any addable type including :class:`~decimal.Decimal` or - :class:`~fractions.Fraction`.) If the input iterable is empty, the - output iterable will also be empty. + :class:`~fractions.Fraction`.) + + Usually, the number of elements output matches the input iterable. + However, if the keyword argument *initial* is provided, the + accumulation leads off with the *initial* value so that the output + has one more element than the input iterable. Roughly equivalent to:: - def accumulate(iterable, func=operator.add): + def accumulate(iterable, func=operator.add, *, initial=None): 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 + # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) - try: - total = next(it) - except StopIteration: - return + total = initial + if initial is None: + try: + total = next(it) + except StopIteration: + return yield total for element in it: total = func(total, element) @@ -152,6 +161,9 @@ loops that truncate the stream. .. versionchanged:: 3.3 Added the optional *func* parameter. + .. versionchanged:: 3.8 + Added the optional *initial* parameter. + .. function:: chain(*iterables) Make an iterator that returns elements from the first iterable until it is |