Reduce function does not handle empty list

I previously created a recursive function to search for the product of a list. Now I created the same function, but using the reduceand function 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 process an empty list, the problem with the reduction function is simply that it is simply not designed to process an empty list? or is there another reason?

It seems that I can not find any question or something on the network that explains why, I can only find answers to solutions to this problem, no explanation.

+4
source share
2 answers

As written in the documentation:

If there is an optional initializer, it is placed before the iterability elements in the calculation and is used by default when the iterability is empty. If no initializer is specified and the iterability contains only one element, the first element 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
+10
source

reduce()initial value is required to get started. If the sequence has no values ​​and there is no explicit value to start, then it cannot start work and will not have a valid return value. Specify an explicit initial value to allow it to work with an empty sequence:

print (reduce(lambda x, y: x*y, items, 1))
+5

Source: https://habr.com/ru/post/1617655/


All Articles