why do we put a function without parenthesis inside map, filter and reduce functions? Check the code below
def func(n):
return n**2
print(list(map(func,[1,2,3,4,5,6,7]))) # Here in this line of code func is placed inside map function without parenthesis. Why it is not put in this way map(func(),[1,2,3,4,5,6,7])?
Output:
[1, 4, 9, 16, 25, 36, 49]
CodePudding user response:
map
is basically equivalent to the following (very simplified) code:
def map(function_object, sequence):
return [function_object(item) for item in sequence]
As you can see, this function_object
is expected to run only inside this pseudo map
function.
Adding parentheses to a function calls that function, that's not what you want to do in this case - as you want to pass that function object into another function (map
in this case) and tell it to work on a sequence of other items.
Any built-in function in python that requires another function as one of its arguments, like reduce
, filter
etc. uses the same principal.
In other words, if you were to put func()
as in your question as an argument, map
wouldn't get the function, it would get the result returning from that function, because it was already called. In your example that would also be an error, because func
can't be called without arguments.
CodePudding user response:
Reading the Python docs for map
, we can see that map
takes a function and an iterable, and then applies the function for every item in that iterable.
If we were to add brackets to the function, so function()
this would not pass the function object itself, but instead execute such function, and provide whatever the return for the function was.