2

Is there anyway to user map on a list with one fixed parameter without a for loop? for example

def addx(x, y):
  return x + y

print map(addx, 10, [10,20])

output should be 20 and 30

Thanks

gtlambert
  • 11,711
  • 2
  • 30
  • 48
Hassam Sheikh
  • 187
  • 1
  • 2
  • 8

4 Answers4

7

functools.partial() to the rescue:

from functools import partial

map(partial(addx, 10), [10, 20])

Demo:

>>> from functools import partial
>>>
>>> def addx(x, y):
...   return x + y
... 
>>> map(partial(addx, 10), [10, 20])
[20, 30]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • what is the difference between this answer and the one marked correct? memory? – Hassam Sheikh Jan 27 '16 at 18:52
  • @HassamSheikh none really. `partial` is just a helper function to do partial application. But just creating something like `lambda x: add(x, 10)` is just doing the partial application manually – juanpa.arrivillaga May 11 '22 at 23:41
2

You can use the lambda anonymous-function creator to inline a new function with only one argument:

Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def addx(x,y):
...     return x+y
...
>>> map(lambda x: addx(x,10), [10, 20])
[20, 30]
>>>
aghast
  • 14,785
  • 3
  • 24
  • 56
0

You can also use list comprehensions:

def addx(x, y):
    return x + y

print [addx(10, i) for i in [10,20]]
0

You can also use repeat from itertools:

from itertools import repeat

def addx(x, y):
  return x + y

map(addx, repeat(10), [10,20])

Side note: if you are using Executor.map() from ProcessPoolExecutor, it's likely to get into trouble with a lambda method, as the passed function to map should be a top-level module function to be picklable:
https://stackoverflow.com/a/8805244/3366323

mamaj
  • 910
  • 8
  • 8