In Python, one could apply a function foo() to every element of a list by using the built-in function map() as follows:
def foo(x):
return x*x
print map(foo, [1, 2, 3, 4])
This would print as one could guess: 1 4 9 16.
Lets say the function foo() now accepts two arguments instead of one, and is defined as follows:
def foo(x, y):
return x+y
In this case, x is an element of the list, and y is some number which is the same for the whole list. How can we use map() in this case such that foo() is applied on every element of the list, while taking another argument y which is the same for every element?
I would like to be able to do something like:
print map(foo(:, 5), [1, 2, 3, 4])
which should give me: 6 7 8 9.
Is it possible in Python? There could be alternatives for this particular example of adding 'y' to all the elements. But I am looking for an answer that would use map().
You can use a lambda function. This is treated just like a normal function, with the
xvalue being the parameter for your iterator, and the return value beingx+5in this case.For the record, @PaoloMoretti had this in before me 🙂