{"id":25568,"date":"2021-11-23T08:55:57","date_gmt":"2021-11-23T03:25:57","guid":{"rendered":"https:\/\/python-programs.com\/?p=25568"},"modified":"2021-11-23T08:55:57","modified_gmt":"2021-11-23T03:25:57","slug":"python-itertools-accumulate-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-itertools-accumulate-function-with-examples\/","title":{"rendered":"Python Itertools.accumulate() Function with Examples"},"content":{"rendered":"

Itertools Module:<\/strong><\/p>\n

The Python itertools module is a collection of tools for working with iterators.<\/p>\n

Iterators are simply data types that can be used in a for loop. The list is the most commonly used iterator in Python.<\/p>\n

Requirements for using itertools<\/strong><\/p>\n

Before using, the itertools module must be imported. Because we want to work with operators, we must also import the operator module.<\/p>\n

The Itertools module is a collection of functions.<\/p>\n

Itertools.accumulate() Function:<\/strong><\/p>\n

This iterator accepts two arguments:<\/p>\n

the iterable target and the function to be followed at each iteration of value in target. If no function is specified, addition is performed by default. If the input iterable is empty, so will the output iterable.<\/p>\n

This function generates an iterator that iterates through the results of a function.<\/p>\n

Syntax:<\/strong><\/p>\n

itertools.accumulate(iterable[, func])<\/pre>\n

Parameter Values<\/strong><\/p>\n

iterable:<\/strong> This is Required. Elements to be gathered or accumulated<\/p>\n

function:<\/strong> This is Optional. Iterables are accumulated using this function.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List = [4, 2, 1, 5, 3]<\/pre>\n

Output:<\/strong><\/p>\n

The cumulative of the given list = [4, 6, 7, 12, 15]<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List = [2, 3, 4, 1, 5]\r\nGiven function = lambda a, b: a*b<\/pre>\n

Output:<\/strong><\/p>\n

[2, 6, 24, 24, 120]<\/pre>\n

Itertools.accumulate() Function with Examples in Python<\/h2>\n