Search code examples
python-3.xreducefunctools

python 3 functools.reduce gives 0 if not literal list given


I am trying reduce in python and getting 0 when expecting other values:

In [1]: from functools import reduce

In [2]: reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
Out[2]: 24

In [3]: def multiply(x, y): return x * y

In [4]: reduce( multiply, [1, 2, 3, 4] )
Out[4]: 24

In [5]: reduce( multiply, range(5) )
Out[5]: 0

In [6]: reduce( multiply, list(range(5)) )
Out[6]: 0

[...]    

In [11]: L = list(range(5))

In [12]: L
Out[12]: [0, 1, 2, 3, 4]

In [13]: reduce(multiply, L)
Out[13]: 0

Why am I getting 0 when not entering a literal list? How can I reduce arbitrary lists? What am I missing?


Solution

  • Python's range starts with 0, not 1. 0 times anything causes the 0 you're always getting...