Home > Enterprise >  Python.: Why product of empty list output is "1"?
Python.: Why product of empty list output is "1"?

Time:09-15

I am using 'prod' method from 'math' package to find the product of a list. Somehow I don't understand why the output is 1 for below operation although its an empty list.

from math import prod

a = [1,2,3]

print(prod(a[:0]))
1

print(bool(a[:0]))
False

CodePudding user response:

Have a look at the description at math module. If the list is empty the returned value is 1

math.prod(iterable, *, start=1)

Calculate the product of all the elements in the input iterable. The default start value for the product is 1.

When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.

CodePudding user response:

This is the usual mathematical convention, which is quite natural.

The sum of no element is defined as 0. (If you append x, the new sum is 0 x.)

The product of no element is defined as 1. (If you append x, the new product is 1.x .)


For a similar reason, the minimum of no element is ∞ and the maximum is -∞. The union of no set is the empty set. The intersection of no set is the universe. The logical or of no boolean is false. The logical and of no boolean is true.

  • Related