1
def multiply(x):
    return (x*x)
def add(x):
    return (x+x)

funcs = [multiply, add]
for i in range(5):
    value = list(map(lambda x: x(i), funcs))
    print(value)

So I understand that map is used to apply a function/first arg to every item in the list/second arg. What I dont understand is how its being handled on this list of functions.

Output:

[0, 0]

[1, 2]

[4, 4]

[9, 6]

[16, 8]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Arsh Khan
  • 21
  • 3
  • For every iteration of i, from 0 to 4, you are taking the input i and multiplying it by itself, hence the first element in each list of 0*0, 1*1, 2*2, 3*3, 4*4 and also adding each element to itself, hence hte second element in each list, 0+0, 1+1, 2+2, 3+3, 4+4. The functions are being applied as you entered them in the list: first run multiply function then apply add function – rmilletich Apr 25 '18 at 19:03
  • 1
    Possible duplicate: [Understanding the map function](https://stackoverflow.com/questions/10973766/understanding-the-map-function) – jpp Apr 25 '18 at 19:04
  • BTW: this is not really the usual use of `map`, which might be causing your confusion. Usually you just have a single function (e.g., `multiply`) which you want to apply to a list or iterable (e.g., `range(5)`). – RishiG Apr 25 '18 at 19:06
  • it applies two functions to numerals from 1 to 5, just that. – Abr001am Apr 25 '18 at 19:06
  • Possible duplicate of [Understanding the map function](https://stackoverflow.com/questions/10973766/understanding-the-map-function) – Aniket Bote Apr 25 '18 at 19:12

2 Answers2

1

Let's try pulling this out of a loop and see what happens.

Your lambda x: x(i) is calling each function with the argument i and map (roughly) turns this into a list.

list(map(lambda x: x(0), funcs)) -> [0,0]

This is the same as saying: [multiply(0), add(0)].

If we try again with 1:

list(map(lambda x: x(0), funcs)) -> [1,2]

This is the same as saying: [multiply(1), add(1)].

The function that you are applying, the first argument to map, is your lambda. That happens to be a higher order function that returns the result of it's input.

A similar way to rewrite this program would be:

def multiply_and_add(i):
    return [multiply(i), add(i)]

result = map(multiply_and_add, range(5))

for value in result
    print(value)
munk
  • 12,340
  • 8
  • 51
  • 71
0

Your map here is used on an array of function. So, for each function it will execute the lambda on it

In the lambda, you have x: x(i) Here, x is the current function (so multiply or add).
And i is your current iteration of the loop (so 0-4).

For example, the 1st time it enters the loop, i == 0. The map function runs multiply 1st, so it returns 0*0, then it runs the add and returns 0+0. So, the output of value is [0,0]

Liora Haydont
  • 1,252
  • 1
  • 12
  • 25