I have the following code snippet but it is giving me the type error above. What I basically wanted to do is add two to every element and reduct it to a single sum, but it didnt work. How can we achieve this??
import functools
list1 = [1,2,3,4]
result = functools.reduce(lambda x:x 2, list1)
print(result)
Update:
It works when I do the following though:
list1 = [1,2,3,4]
result = functools.reduce(lambda x,y:x y, list1)
print(result)
CodePudding user response:
reduce()
requires a lambda function which takes 2 arguments.
The first argument is the collector.
But here, so that 2
is applied also on the first argument, you have to give the initial value 0.
import functools
list1 = [1,2,3,4]
result = functools.reduce(lambda acc, el: acc el 2, list1, 0)
print(result) ## sum([3, 4, 5, 6]) = 18
You basically want to do a normal summing reduce(lambda x, y: x y, lst)
=> sum(lst)
and a map(lambda x: x 2, l)
which is expressed in a more pythonic way as a list comprehension:
l = [1, 2, 3, 4]
sum([x 2 for x in l]) # most pythonic!
## 18
sum(map(lambda x: x 2, l))
## 18
or:
import functools
l = [1, 2, 3 ,4]
result = functools.reduce(lambda x, y: x y, [x 2 for x in l])
result ## 18
or:
import functools
l = [1, 2, 3 ,4]
result = functools.reduce(lambda x, y: x y, map(lambda x: x 2, l))
result ## 18
CodePudding user response:
The callable passed to the reduce
function needs to take two arguments to aggregate the current result with the next item from the given iterable:
import functools
list1 = [1, 2, 3, 4]
result = functools.reduce(lambda x, y: x y 2, list1, 0)
print(result)
This outputs:
18