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.
The JavaScript exception "reduce of empty array with no initial value" occurs when a reduce function is used.
The list() function returns an empty list if no arguments is passed to it.
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With