Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack nested list for arguments to map()

I'm sure there's a way of doing this, but I haven't been able to find it. Say I have:

foo = [
    [1, 2],
    [3, 4],
    [5, 6]
]

def add(num1, num2):
    return num1 + num2

Then how can I use map(add, foo) such that it passes num1=1, num2=2 for the first iteration, i.e., it does add(1, 2), then add(3, 4) for the second, etc.?

  • Trying map(add, foo) obviously does add([1, 2], #nothing) for the first iteration
  • Trying map(add, *foo) does add(1, 3, 5) for the first iteration

I want something like map(add, foo) to do add(1, 2) on the first iteration.

Expected output: [3, 7, 11]

like image 440
binaryfunt Avatar asked Dec 05 '15 20:12

binaryfunt


People also ask

How do you unpack a list in an argument in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

How many arguments can be passed to map () function?

The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object.

How do I pop a nested list?

When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method. If you know the index of the item you want, you can use pop() method.


3 Answers

It sounds like you need starmap:

>>> import itertools
>>> list(itertools.starmap(add, foo))
[3, 7, 11]

This unpacks each argument [a, b] from the list foo for you, passing them to the function add. As with all the tools in the itertools module, it returns an iterator which you can consume with the list built-in function.

From the documents:

Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c).

like image 103
Alex Riley Avatar answered Sep 24 '22 19:09

Alex Riley


try this:

 foo = [
    [1, 2],
    [3, 4],
    [5, 6]]

def add(num1, num2):
        return num1 + num2

print(map(lambda x: add(x[0], x[1]), foo))
like image 41
linluk Avatar answered Sep 21 '22 19:09

linluk


There was another answer with a perfectly valid method (even if not as readable as ajcr's answer), but for some reason it was deleted. I'm going to reproduce it, as it may be useful for certain situations

>>> map(add, *zip(*foo))
[3, 7, 11]
like image 24
binaryfunt Avatar answered Sep 24 '22 19:09

binaryfunt