Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map over a function with multiple arguments in python

I'm looking to map over a function with lists for specific arguments.

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

list1 = [1, 2, 3]
list2 = [3, 4, 5]

After some research I have been able to successfully do it using map and a lambda function.

list(map(lambda x, y: add(x, y), list1, list2))

I was wondering, is it better to do this using an iterator? I tried the following but couldn't figure it out:

[add(x, y), for x, y in list1, list2]

or

[add(x, y), for x in list1 for y in list2]

Thanks in advance!

like image 345
Matt W. Avatar asked Dec 17 '17 20:12

Matt W.


People also ask

Can Map function have more than 2 arguments?

We can pass multiple iterable arguments to map() function, in that case, the specified function must have that many arguments. The function will be applied to these iterable elements in parallel. With multiple iterable arguments, the map iterator stops when the shortest iterable is exhausted.

How do you pass multiple arguments on a map?

To pass multiple arguments to the map() function:Pass the handler function and the arguments to the functools. partial() method. Pass the result and the iterable to the map() function. The handler function will get called the arguments on each iteration.

Can you pass multiple arguments to a function in Python?

Passing multiple arguments to a function in Python:We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.

How many arguments can map function have in Python?

function can be any Python callable that accepts two arguments and returns a value. iterable can be any Python iterable.


1 Answers

There is no need to use a lambda expression here, you can pass a reference to te function directly:

list(map(add, list1, list2))

In case you want to use list comprehension, you can use zip:

[add(x, y) for x, y in zip(list1, list2)]

zip takes n iterables, and generate n-tuples where the i-th tuple contains the i-th element of every iterable.

In case you want to add a default value to some parameters, you can use partial from functools. For instance if you define a:

def add (x, y, a, b):
    return x + y + a + b
from functools import partial

list(map(partial(add, a=3, b=4), list1, list2))

Here x and y are thus called as unnamed parameters, and a and b are by partial added as named parameters.

Or with list comprehension:

[add(x, y, 3, 4) for x, y in zip(list1, list2)]
like image 189
Willem Van Onsem Avatar answered Oct 12 '22 03:10

Willem Van Onsem