Reputation: 23
I need some help to count the numbers of elements in a list by using the reduce function.
def lenReduce(L):
return reduce(lambda x: x + 1, L)
With this one I get the following error message:
TypeError: <lambda>() takes 1 positional argument but 2 were given
Greetings from Berlin. ;-)
Upvotes: 1
Views: 5380
Reputation: 1
All previous answers seemed not work since it will add 1 to the first element of the given list every iteration. Try this trick, add 0 as the first element of the list, then decrease the return value by 1.
lenReduce = lambda L: reduce(lambda x, y: x+1, [0]+L, 0) - 1
Upvotes: 0
Reputation: 41
lenReduce([5,3,1])
returns 7
What this means is, for the very first time when the lambda function is invoked, count
is set to 5
and item
is set to 3
which are the first two elemets of the list. From the next invocation of the lambda function, count
is incremented. Therefore the solution does not work.
The solution is to set the count to a value of our choosing rather than the first element of the list. To do that, invoke reduce with three arguments.
def lenReduce(L):
return reduce(lambda count, item: count + 1, L, 0)
In the above call of reduce, count
is set to 0
and item will be set to the elements of the list starting from index 0
on each iteration.
lenReduce([3,2,1])
outputs 3
which is the desired result.
Upvotes: 4
Reputation: 531275
The function argument to reduce
takes two arguments: the return value of the previous call, and an item from the list.
def counter(count, item):
return count + 1
In this case, you don't really care what the value of item
is; simply passing it to counter
means you want to return the current value of the counter plus 1.
def lenReduce(L):
return reduce(counter, L)
or, using a lambda
expression,
def lenReduce(L):
return reduce(lambda count, item: count + 1, L)
Even though your function ignores the second argument, reduce
still expects to be able to pass it to the function, so it must be defined to take two arguments.
Upvotes: 1