Is There a Multiplication Function in Python Equivalent to sum()?

DDD
Release: 2024-10-23 06:00:03
Original
371 people have browsed it

Is There a Multiplication Function in Python Equivalent to sum()?

Multiplication Function Analogous to sum()

The built-in Python function sum() provides a convenient way to calculate the sum of numbers in an iterable. However, a direct counterpart for multiplication is notably absent.

Search for a Multiplication Function

The question arises: is there an established function that performs the multiplication equivalent of sum()? Despite diligent searching, no such function within the native Python library has been identified.

Developing a Custom Function

Nevertheless, creating a custom function to meet this need is straightforward. Using functools.reduce and operator.mul allows you to achieve this functionality:

<code class="python">from functools import reduce
import operator

def product(iterable, initial=1):
    return reduce(operator.mul, iterable, initial)

result = product([3, 4, 5])
print(result)  # Output: 60</code>
Copy after login

The product() function takes an iterable and an optional initial value, defaulting to 1. It then accumulates the product of all elements in the iterable from left to right, effectively calculating the multiplication equivalent of sum().

This custom function satisfies the need for a multiplication function in Python, mimicking the behavior of sum() but for a multiplication operation.

The above is the detailed content of Is There a Multiplication Function in Python Equivalent to sum()?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!