The itertools.accumulate
function in Python's itertools
module returns an iterator that yields accumulated sums, or accumulated results of other binary functions, specified via the func
parameter. It is useful for performing cumulative operations on iterable data.
Table of Contents
- Introduction
itertools.accumulate
Function Syntax- Examples
- Basic Usage
- Using a Different Binary Function
- Using
accumulate
with a Lambda Function
- Real-World Use Case
- Conclusion
Introduction
The itertools.accumulate
function creates an iterator that returns accumulated sums or results of a specified binary function. By default, it performs cumulative summation, but you can pass a different binary function to customize the operation.
itertools.accumulate Function Syntax
Here is how you use the itertools.accumulate
function:
import itertools
iterator = itertools.accumulate(iterable, func=operator.add, *, initial=None)
Parameters:
iterable
: The input iterable whose accumulated values are to be computed.func
: Optional. A binary function (default isoperator.add
) to perform the accumulation.initial
: Optional. A starting value to include in the accumulation.
Returns:
- An iterator that yields accumulated values.
Examples
Basic Usage
Create an iterator that yields accumulated sums of numbers in a list.
Example
import itertools
numbers = [1, 2, 3, 4, 5]
accumulated_sums = itertools.accumulate(numbers)
print(list(accumulated_sums))
Output:
[1, 3, 6, 10, 15]
Using a Different Binary Function
Use the operator.mul
function to accumulate the product of elements.
Example
import itertools
import operator
numbers = [1, 2, 3, 4, 5]
accumulated_products = itertools.accumulate(numbers, func=operator.mul)
print(list(accumulated_products))
Output:
[1, 2, 6, 24, 120]
Using accumulate
with a Lambda Function
Use a lambda function to accumulate the maximum value.
Example
import itertools
numbers = [1, 5, 2, 6, 3, 7]
accumulated_max = itertools.accumulate(numbers, func=lambda x, y: max(x, y))
print(list(accumulated_max))
Output:
[1, 5, 5, 6, 6, 7]
Real-World Use Case
Cumulative Sum of Sales
Calculate the cumulative sum of daily sales.
Example
import itertools
daily_sales = [100, 200, 150, 300, 250]
cumulative_sales = itertools.accumulate(daily_sales)
print(list(cumulative_sales))
Output:
[100, 300, 450, 750, 1000]
Conclusion
The itertools.accumulate
function is used for generating accumulated results from an iterable. Whether you need to perform cumulative summation, multiplication, or any other binary operation, accumulate
provides a flexible and efficient way to handle such tasks.
Comments
Post a Comment
Leave Comment