Python – Itertools.accumulate()
Python itertools module is a collection of tools for handling iterators.
According to the official documentation:
“Module [that] implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML… Together, they form an ‘iterator algebra’ making it possible to construct specialized tools succinctly and efficiently in pure Python.” this basically means that the functions in itertools “operate” on iterators to produce more complex iterators.
Simply put, iterators are data types that can be used in a for loop. The most common iterator in Python is the list.
Let’s create a list of strings and named it colors. We can use a for loop to iterate the list like:
red orange yellow green
There are many different kinds of iterables but for now, we will be using lists and sets.
Requirements to work with itertools
Must import the itertools module before using. We have to also import the operator module because we want to work with operators.
import itertools import operator ## only needed if want to play with operators
Itertools module is a collection of functions. We are going to explore one of these accumulate() function.
Note: For more information, refer to Python Itertools
This iterator takes two arguments, iterable target and the function which would be followed at each iteration of value in target. If no function is passed, addition takes place by default. If the input iterable is empty, the output iterable will also be empty.
itertools.accumulate(iterable[, func]) –> accumulate object
This function makes an iterator that returns the results of a function.
iterable & function
Now its enough of the theory portion lets play with the code
1 2 6 24 120
The operator.mul takes two numbers and multiplies them.
operator.mul(1, 2) 2 operator.mul(2, 3) 6 operator.mul(6, 4) 24 operator.mul(24, 5) 120
Now in the next example, we will use the max function as it takes a function as a parameter also.
5 5 6 6 6 9 9
5 max(5, 3) 5 max(5, 6) 6 max(6, 2) 6 max(6, 1) 6 max(6, 9) 9 max(9, 1) 9
Note: The passing function is optional as if you will not pass any function items will be summed i.e. added by default.
This return accumulate of items of difference between sets.
Code to explain
0 4 11
Please Login to comment...