0

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?

2

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

5 Comments

I like the lambda function solution. Should I worry about any possible impact on speed, compared to a plain call to map?
@RickyRobinson: There is some indirection, so all three options will cost you some speed. All three will have close to the same overhead though.
Ok. The thing is I'm trying to convert all my for loops into map calls, so I wouldn't wanna go back to the previous situation in terms of speed.
@RickyRobinson: I'd try out different approaches, it could be that partial() is going to be faster (it's implemented in C), for example, saving a stack push.
@RickyRobinson: I added a speed comparison for your enjoyment; functools.partial() is going to be closest to calling the wrapped function directly.
2
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]

Comments

1

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]

1 Comment

OK, I wanted to avoid having to write a function for each parameter in use, but if there is no other way, then OK. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.