I'm not sure why the code below works. According to docs, map only takes one function as the first argument and applies it to one or more iterables, depending on how many parameters the function takes.
map(function, iterable..)
However, in place of iterables, you can pass multiple functions and somehow they are treated as iterables. Somehow this line is taking the functions add, square and str and treating them as iterables.
How are functions being considered valid iterables?
def add(x):
return x + x
def square(x):
return x * x
nums = [1, 2, 3, 4, 5]
for i in nums:
vals = list(map(lambda x: x(i), (add, square, str)))
print(vals)
returns:
[2, 1, '1']
[4, 4, '2']
[6, 9, '3']
[8, 16, '4']
[10, 25, '5']
*EDIT
Martijn answered the question. This code does the same thing but breaks it out of the lambda function showing how add, square, str are functions being iterated upon.
def add(x):
return x + x
def square(x):
return x * x
def act_on_iter(iter_obj, i):
return iter_obj(i)
nums = [1, 2, 3, 4, 5]
for i in nums:
vals = list(map(act_on_iter, (add, square, str), [i] * 3))
print(vals)
returns the same
[2, 1, '1']
[4, 4, '2']
[6, 9, '3']
[8, 16, '4']
[10, 25, '5']