Error in lambda function..!

Rob Cliffe rob.cliffe at btinternet.com
Sat Aug 29 05:02:30 EDT 2020



On 29/08/2020 08:58, Shivlal Sharma wrote:
> from functools import*
> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> add = reduce(lambda a : a + 1, nums)
> print(add)
>
> error: -
> TypeError                                 Traceback (most recent call last)
> <ipython-input-15-684b5d4fac30> in <module>()
>        1 from functools import*
>        2 nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> ----> 3 add = reduce(lambda a : a + 1, nums)
>        4 print(add)
>
> TypeError: <lambda>() takes 1 positional argument but 2 were given
When you write
     lambda a :
you are defining a function that takes **one** argument, viz. a.
It's the same as if you wrote:
     def myfunc(a): return a+1
and then
     add = reduce(myfunc, nums)
But reduce always calls your supplied function with **two** arguments.  
Hence the error.
I don't know exactly what you are trying to do, but if you wrote
     add = reduce(lambda a,b: a+1, nums)
or equivalently
     def myfunc(a,b): return a+1
     add = reduce(myfunc, nums)
reduce would call your lambda function succesively with arguments
     (1,2)    # which would return 1+1 i.e. 2
     (2,3)    # use previous result (2) and next number in the sequence 
(3); returns 2+1 i.e. 3
     (3,4)    # use previous result (3) and next number in the sequence (4)

     .....
     (8,9)    # returns 8+! i.e. 9
and finally 9 would be printed.

If you want to watch what is happening try
     def myfunc(a,b):
         print(f"Myfunc({a},{b})")
         return a+1
     add = reduce(myfunc, nums)

Try
     from functools import *
     help(reduce)
for an explanation of how reduce works.  Note that the first sentence 
starts "Apply a function of two arguments"
Best wishes
Rob Cliffe



More information about the Python-list mailing list