map lambda x,y with a constant x

23,281

Solution 1

You can use itertools.starmap

a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y))
a = list(a)

and you get your desired output.

BTW, both itertools.imap and Python3's map will accept the following:

itertools.imap(lambda x,y: x+y, itertools.repeat(x), y)

The default Python2's map will not stop at the end of y and will insert Nones...


But a comprehension is much better

[x + num for num in y]

Solution 2

Also you could use closure for this

x='a'
f = lambda y: x+y
map(f, ['1', '2', '3', '4', '5'])
>>> ['a1', 'a2', 'a3', 'a4', 'a5']

Solution 3

Python 2.x

from itertools import repeat

map(lambda (x, y): x + y, zip(repeat(x), y))

Python 3.x

map(lambda xy: ''.join(xy), zip(repeat(x), y))

Solution 4

def prependConstant(x, y):
  return map(lambda yel: x + yel, y)

Solution 5

['a' + x for x in y]

or if you really need a callable:

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

[f('a', x) for x in y]
Share:
23,281
Jonathan Livni
Author by

Jonathan Livni

python, django, C++ and other vegetables...

Updated on September 12, 2020

Comments

  • Jonathan Livni
    Jonathan Livni almost 4 years

    What would be an elegant way to map a two parameter lambda function to a list of values where the first parameter is constant and the second is taken from a list?

    Example:

    lambda x,y: x+y
    x='a'
    y=['2','4','8','16']
    

    expected result:

    ['a2','a4','a8','a16']
    

    Notes:

    • This is just an example, the actual lambda function is more complicated
    • Assume I can't use list comprehension
  • Adam Wagner
    Adam Wagner over 12 years
    @JBernardo, did they take 'unpacking in signature' away? I seem to remember something along those lines.
  • Cody Hess
    Cody Hess over 12 years
    +1 for suggesting pythonic list comprehension instead of that gross ol' map function (= -- although I just noticed the asker states "assume I can't use list comprehension"
  • JBernardo
    JBernardo over 12 years
    Yes, that's why I suggested starmap on my answer.