Search code examples
pythonfunctional-programmingreduce

python - Length of a list with the reduce() function


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


Solution

  • 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.