Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce function doesn't handle an empty list

I previously created a recursive function to find the product of a list. Now I've created the same function, but using the reduce function and lamdba.

When I run this code, I get the correct answer.

items = [1, 2, 3, 4, 10]
print(reduce(lambda x, y: x*y, items))

However, when I give an empty list, an error occurs - reduce() of empty sequence with no initial value. Why is this?

When I created my recursive function, I created code to handle an empty list, is the issue with the reduce function just that it just isn't designed to handle and empty list? or is there another reason?

I cannot seem to find a question or anything online explaining why, I can only find questions with solutions to that particular persons issue, no explanation.

like image 263
Chris Avatar asked Nov 26 '15 19:11

Chris


People also ask

Can you reduce an empty array in JavaScript?

The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used.

Which function will return an empty list?

The list() function returns an empty list if no arguments is passed to it.

How do you reduce a list in Python?

Python offers a function called reduce() that allows you to reduce a list in a more concise way. The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.

Why reduce is not totally recommended in Python 3?

The arguments against reduce are that it tends to be misapplied, harms readability and doesn't fit in with the non-functional orientation of Python.


Video Answer


2 Answers

As it is written in the documentation:

If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

So if you want your code to work with an empty list, you should use an initializer:

>>> reduce(lambda x, y: x*y, [], 1)
1
like image 158
julienc Avatar answered Oct 02 '22 21:10

julienc


reduce() requires an initial value to start its operation from. If there are no values in the sequence and no explicit value to start from then it cannot begin operation and will not have a valid return value. Specify an explicit initial value in order to allow it to operate with an empty sequence:

print (reduce(lambda x, y: x*y, items, 1))
like image 22
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 22:10

Ignacio Vazquez-Abrams