Returning the product of a list

python multiply all elements in list together
multiply each element of a list by a number in python
python product of two lists
python multiply function
python list multiplication operator
python multiply list by float
how to multiply two lists in python
numpy product

Is there a more concise, efficient or simply pythonic way to do the following?

def product(list):
    p = 1
    for i in list:
        p *= i
    return p


I actually find that this is marginally faster than using operator.mul:

from operator import mul
# from functools import reduce # python3 compatibility

def with_lambda(list):
    reduce(lambda x, y: x * y, list)

def without_lambda(list):
    reduce(mul, list)

def forloop(list):
    r = 1
    for x in list:
        r *= x
    return r

import timeit

a = range(50)
b = range(1,50)#no zero
t = timeit.Timer("with_lambda(a)", "from __main__ import with_lambda,a")
print("with lambda:", t.timeit())
t = timeit.Timer("without_lambda(a)", "from __main__ import without_lambda,a")
print("without lambda:", t.timeit())
t = timeit.Timer("forloop(a)", "from __main__ import forloop,a")
print("for loop:", t.timeit())

t = timeit.Timer("with_lambda(b)", "from __main__ import with_lambda,b")
print("with lambda (no 0):", t.timeit())
t = timeit.Timer("without_lambda(b)", "from __main__ import without_lambda,b")
print("without lambda (no 0):", t.timeit())
t = timeit.Timer("forloop(b)", "from __main__ import forloop,b")
print("for loop (no 0):", t.timeit())

gives me

('with lambda:', 17.755449056625366)
('without lambda:', 8.2084708213806152)
('for loop:', 7.4836349487304688)
('with lambda (no 0):', 22.570688009262085)
('without lambda (no 0):', 12.472226858139038)
('for loop (no 0):', 11.04065990447998)

Without using lambda:

from operator import mul
reduce(mul, list, 1)

it is better and faster. With python 2.7.5

from operator import mul
import numpy as np
import numexpr as ne
# from functools import reduce # python3 compatibility

a = range(1, 101)
%timeit reduce(lambda x, y: x * y, a)   # (1)
%timeit reduce(mul, a)                  # (2)
%timeit                      # (3)
%timeit ne.evaluate("prod(a)")          # (4)

In the following configuration:

a = range(1, 101)  # A
a = np.array(a)    # B
a = np.arange(1, 1e4, dtype=int) #C
a = np.arange(1, 1e5, dtype=float) #D

Results with python 2.7.5

       |     1     |     2     |     3     |     4     |
 A       20.8 µs     13.3 µs     22.6 µs     39.6 µs     
 B        106 µs     95.3 µs     5.92 µs     26.1 µs
 C       4.34 ms     3.51 ms     16.7 µs     38.9 µs
 D       46.6 ms     38.5 ms      180 µs      216 µs

Result: is the fastest one, if you use np.array as data structure (18x for small array, 250x for large array)

with python 3.3.2:

       |     1     |     2     |     3     |     4     |
 A       23.6 µs     12.3 µs     68.6 µs     84.9 µs     
 B        133 µs      107 µs     7.42 µs     27.5 µs
 C       4.79 ms     3.74 ms     18.6 µs     40.9 µs
 D       48.4 ms     36.8 ms      187 µs      214 µs

Is python 3 slower?

Python, Method 1: Traversal. Initialize the value of product to 1(not 0 as 0 multiplied with anything returns zero). Traverse till the end of the list, multiply every number with​  public List<var> ListOfProducts(string subcategory) { var products = (from p in dataContext.Products join s in dataContext.SubCategories.Where(x => x.SubCatName == subcategory) on p.SubcatId equals s.SubCatId join b in dataContext.Brands on p.BrandId equals b.BrandId select new { Subcategory = s.SubCatName, Brand = b.BrandName, p.ProductName,

reduce(lambda x, y: x * y, list, 1)

Program for product of array, C program to find product of array. // elements. #include <stdio.h>. int product( int ar[], int n). {. int result = 1;. for ( int i = 0; i < n; i++). result = result * ar[i];. return  Here is how to write a method that gives the product of the elements of a list: import functools import operator def product(seq): """Product of a sequence.""" return functools.reduce(operator.mul, seq, 1)

if you just have numbers in your list:

from numpy import prod

EDIT: as pointed out by @off99555 this does not work for large integer results in which case it returns a result of type numpy.int64 while Ian Clelland's solution based on operator.mul and reduce works for large integer results because it returns long.

Python Exercise: Multiply all the numbers in a list, def multiply(numbers): total = 1 for x in numbers: total *= x return total print(​multiply((8, 2, 3, -1, 7))). Sample Output: -336. Pictorial presentation:. Formulae that return a result in to two or more cells (there are various formulae that will do this including MINVERSE(), LINEST() and TRANSPOSE()). These types of array formulas return an array of values as their result and are referred to as multi-cell array formulae .

import operator
reduce(operator.mul, list, 1)

Python: Compute the product of a list of integers, Returns the least common multiple of a list of numbers. Example: from functools import reduce from math import gcd def tips_lcm(nums): return  In retail, a product return is the process of a customer taking previously purchased merchandise back to the retailer, and in turn receiving a refund in the original form of payment, exchange for another item (identical or different), or a store credit.

Well if you really wanted to make it one line without importing anything you could do:

eval('*'.join(str(item) for item in list))

But don't.

Sum and product of an array, function Product(Item : Int_Array) return Integer is compute(sum, product, list(2, 3, 5, 7, 11, 13, 17, 19)); the results are returned in sum and product % The product, a numeric (of type "double") or complex vector of length one. NB: the product of an empty set is one, by definition. S4 methods. This is part of the S4 Summary group generic. Methods for it must use the signature x, , na.rm. References. Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

[Challenge] Product of Everything Else, num_array[i]: product *= n product_list.append(product) #add product to the product_list list product = 1 #restart the product variable return  Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Visual Basic for AVCE, to the list of products bought by the current customer that are displayed in the Return product combo box • Enables the Print receipt command button Returning​  Return a list of all products that are low in inventory (where the inventory in stock is less than 10) and need to be reordered, sorted by the category name and then sorted by product name. Return a list of all category names and category ID, sorted by category ID. Only return the category name and ID values.

Most Efficient Way to Calculate the Product of All Items in a List , Say that I have a list of returns on a financial asset over time and want to know the total compounded return. To get the answer, I need to add 1 to  Products purchased at a Costco location need to be returned at the returns counter at any Costco warehouse. Items ordered online can be returned at any Costco warehouse -or- you can initiate a return through Accepted payment methods differ online and in the warehouse. Please click here for a complete list of accepted payments.