Reputation: 749
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()
.
Upvotes: 3
Views: 206
Reputation: 37259
You can use a lambda function. This is treated just like a normal function, with the x
value being the parameter for your iterator, and the return value being x+5
in this case.
>>> def foo(x, y)
... return x + y
...
>>> l = [1, 2, 3, 4]
>>> map(lambda x: foo(x, 5), l)
[6, 7, 8, 9]
For the record, @PaoloMoretti had this in before me :)
Upvotes: 6
Reputation: 24788
One way to do this is with functools.partial
:
>>> from functools import partial
>>> def foo(x, y):
... return x + y
...
>>> l = [1, 2, 3, 4]
>>> map(partial(foo, y=2), l)
[3, 4, 5, 6]
>>>
Another way is to change the way you define the function:
>>> def foo(y):
... def inner(x):
... return x + y
... return inner
...
>>> map(foo(2), l)
[3, 4, 5, 6]
>>>
Incidentally, using lambda
would be the most straightforward way to do this, as Paolo Moretti said. Any particular reason why you have to use map()
the way you described?
Upvotes: 5