Home > Enterprise >  How to apply a function in a pairwise fashion in python with one argument and a list of arguments
How to apply a function in a pairwise fashion in python with one argument and a list of arguments

Time:11-04

What is the best and fastest way to apply a function in python when:

  1. A function takes two arguments
  2. Argument #1 is a predefined value
  3. Argument #2 is a list of values
  4. I need to apply the function with Argument #1 and every element from Argument #2 list

I can do something like this:

result = []
for argument_from_list in arguments_list:
  result.append(my_func(predefined_value, argument_from_list))

I was also thinking about map and enclosing the value in [] but:

With multiple iterables, the iterator stops when the shortest iterable is exhausted

So I could not come up with a solution involving list comprehension and some functional method although I'm sure it's possible and probably faster.

CodePudding user response:

As a list comprehension:

result = [my_func(predefined_value, argument_from_list) for argument_from_list in arguments_list]

If you want to use map, it takes a function that takes a single argument, so either you'll have to get a function that takes a single argument.

Using map and lambda:

result = list(map(lambda arg: my_func(predefined_value, arg), arguments_list))

Using map and partial function application:

from functools import partial

result = list(map(partial(my_func, predefined_value), arguments_list))

Alternatively, if you want to zip things up, that's possible too. There's a variant of map in the itertools standard library.

Using itertools.starmap and itertools.repeat:

from itertools import starmap, repeat
result = list(starmap(my_func, zip(repeat(predefined_value), arguments_list)))

I recommend going with the list comprehension.

  • Related