Question

Here's a stupid example:

def add_x_to_input(x,k):
   return x + k

myList = [1,2,3,4]
myNewList = map(add_x_to_input???, myList)

How do I specify the parameter x of add_x_to_input, when I give it as input function to map?

Was it helpful?

Solution

You could use functools.partial():

from functools import partial
map(partial(add_x_to_input, some_value_for_x), myList)

or you could use a lambda (an anonymous, in-line function):

map(lambda k: add_x_to_input(some_value_for_x, k), myList)

or you could define an explicit new function:

def wrapping_function(k):
    return add_x_to_input(some_value_for_x, k)

map(wrapping_function, myList)

If you are after sheer speed, the functools.partial() approach wins that hands-down; it is implemented in C code and avoids an extra Python stack push:

>>> import timeit
>>> L = range(10)
>>> def foo(a, b): pass
... 
>>> def p(b): return foo(1, b)
... 
>>> timeit.timeit('map(p, L)', 'from __main__ import foo, L; from functools import partial; p = partial(foo, 1)')
3.0008959770202637
>>> timeit.timeit('map(p, L)', 'from __main__ import foo, L; p = lambda b: foo(1, b)')
3.8707590103149414
>>> timeit.timeit('map(p, L)', 'from __main__ import foo, L, p')
3.9136409759521484

OTHER TIPS

def add_x_to_input(x,k):
   return x + k

myList = [1,2,3,4]
x = 5
myNewList = map(lambda k:add_x_to_input(x,k), myList)

or just:

myNewList = [x+k for k in myList]

Define a closure:

In [61]: def add_x_to_input(x,k):
    ...:    return x + k

In [62]: def add_1(x):
    ...:     return add_x_to_input(x,1)

In [63]: add_1(1)
Out[63]: 2

In [64]: list = [1,2,3]

In [65]: map(add_1, list)
Out[65]: [2, 3, 4]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top