7

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.

2 Answers 2

22

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ah okay, I was confused because I found a code example of reduce where it took the parameters (function, iterable, initializer). I thought that the list was somehow being used as the initializer, but thanks for clarifying!
@Chris iterable[0] is used as the initializer if initializer is None, but in your case [][0] does not exist hence the error.
5

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.