Search code examples
pythonmap-function

I have difficulty using map function in python


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]

Solution

  • 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