1

I am very new to python.
I researched about my problem but couldn't get the excepted answer.
What I don't understand here is how is myfunc being called as it has no parameters like myfunc() and how is argument (n) taking two arguments(apple and banana)?

    def myfunc(n):
        return len(n)

    x = list(map(myfunc,('apple', 'banana')))
    print(x)
   
    output:
    [5,6]
PilouPili
  • 2,601
  • 2
  • 17
  • 31
Usus
  • 89
  • 4
  • 2
    It's not taking two arguments. You're calling `myfunc` first with `'apple'`, and then calling it again with `'banana'`. – khelwood Sep 21 '20 at 12:14
  • 2
    It doesn't take two arguments, but one. Once the argument is `apple` (then the returned length is 5, as it has five letters) and then the argument is `banana`, with the lenght 6. What you might have not known that strings behave like collections (of characters) in Python. – Maciek Sep 21 '20 at 12:14

2 Answers2

5

map(fun, iterable) applies the fun function to each element in the iterable (e.g. a list) and returns the each of the output in a list.

The reason why the function myfunc has no argument is that you should see it just as an argument of the map function.

Try to think of map, for your example, like this:

[5, 6] = [myfunc('apple'), myfunc('banana')]

internally, the map function is doing something like:

def map(myfunc, iterable):
    returns = []
    for i in iterable:
        returns.append(myfunc(i))
    return returns
JacoSolari
  • 1,226
  • 14
  • 28
2

Map doesn't actually take a function, it takes the reference to a function. References are passed without the parentheses and hence you can't supply arguments manually, map does that for you. For eg. If we want to convert anything to integer, we'll use

int(50.65)

But map takes only the reference to function.

map(int, input().split())