Reduce function doesn't handle an empty list

Question:

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.

Asked By: Chris

||

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
Answered By: 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))
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.