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!
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.
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.
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.
function can be any Python callable that accepts two arguments and returns a value. iterable can be any Python iterable.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With