Matt W.
Matt W.

Reputation: 3722

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!

Upvotes: 10

Views: 16511

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

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)]

Upvotes: 18

Related Questions