Function reverse parameter

Hi,

For the function I have reversed the parameter.
It is perfectly fine correct.
It is yielding same result
square = lambda x: x*x

def mapit(listy,func):
return [func(e) for e in listy]

mapit(range(5), square)

def mapit(func,listy):
return [func(e) for e in listy]

mapit(square, range(5))

Thanks and Regards,
Subho

Hi, could you please write the code in using the markdown syntax and also re-iterate your question?

square = lambda x: x*x

def mapit(listy,func):
return [func(e) for e in listy]

mapit(range(5), square)

def mapit(func,listy):
return [func(e) for e in listy]

mapit(square, range(5))

Hi @subhobrata1,

If I understand, you want to know why reversing parameters still works?

It works because at the time of function call you specified the parameters correctly i.e mapit(square, range(5)

If you still gave parameters such as mapit(range(5), square), you would get the below error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-f0e9eda4667a> in <module>
----> 1 mapit2(range(5), square)

<ipython-input-7-7b805ff46490> in mapit2(func, listy)
      1 def mapit2(func, listy):
----> 2     return [func(i) for i in listy]

TypeError: 'function' object is not iterable

This is easy to miss, so although you are free to specify the parameters in any order, it’s important to call them in in the same order

Bonus: Python functions also allow for keyword arguments which you can specify in any order. Below is the same mapit function but with keyword arguments.

def mapit(func = None, listy = None):
    return [func(i) for i in listy]

mapit(func=square, listy = range(5))
[0, 1, 4, 9, 16]
mapit(listy = range(5),func=square)
[0, 1, 4, 9, 16]

More here-> Python positional and keyword arguments

Does this answer your question?

1 Like

Thanks will check this