How to do multiple arguments to map function where one remains the same in python?
Solution 1:
One option is a list comprehension:
[add(x, 2) for x in [1, 2, 3]]
More options:
a = [1, 2, 3]
import functools
map(functools.partial(add, y=2), a)
import itertools
map(add, a, itertools.repeat(2, len(a)))
Solution 2:
The docs explicitly suggest this is the main use for itertools.repeat
:
Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to
map()
for invariant parameters to the called function. Also used withzip()
to create an invariant part of a tuple record.
And there's no reason for pass len([1,2,3])
as the times
argument; map
stops as soon as the first iterable is consumed, so an infinite iterable is perfectly fine:
>>> from operator import add
>>> from itertools import repeat
>>> list(map(add, [1,2,3], repeat(4)))
[5, 6, 7]
In fact, this is equivalent to the example for repeat
in the docs:
>>> list(map(pow, range(10), repeat(2)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
This makes for a nice lazy-functional-language-y solution that's also perfectly readable in Python-iterator terms.
Solution 3:
Use a list comprehension.
[x + 2 for x in [1, 2, 3]]
If you really, really, really want to use map
, give it an anonymous function as the first argument:
map(lambda x: x + 2, [1,2,3])
Solution 4:
Map can contain multiple arguments, the standard way is
map(add, a, b)
In your question, it should be
map(add, a, [2]*len(a))
Solution 5:
The correct answer is simpler than you think. Simply do:
map(add, [(x, 2) for x in [1,2,3]])
And change the implementation of add to take a tuple i.e
def add(t):
x, y = t
return x+y
This can handle any complicated use case where both add parameters are dynamic.