10

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!

1
  • 1
    Use zip for a list comprehsion Commented Dec 17, 2017 at 20:41

1 Answer 1

18

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)]
Sign up to request clarification or add additional context in comments.

4 Comments

ok, awesome. what if there were a couple other arguments that didn't change. like add(a, b, x, y), and you want to set a = 3, b = 4, and then iterate through the lists for x and y?
your edit answered my above Q. Also, it threw an error I think because of the comma you have after add(x, y),. Once I removed that it worked.
@MattW.: indeed, thanks for spotting it, removed it now :)
Thanks for your answer! fixed my issue, and was a great explanation. I'll accept as soon as SO lets me. cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.