Python Forum
Unpacking nested lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unpacking nested lists (/thread-25884.html)



Unpacking nested lists - yonatan776 - Apr-14-2020

Hey, I beleive it's a relatively simple quiestion although i didn't find any simple answer in Google.

I'd like to create a function that unpacks a list of lists and create a new list that sums up the variables which are in the same index.
For instance: [[1,1],[1,3]] ---> [2,4]

or [[1,1,1],[1,0,0],[0,0,100]] ---> [2,1,101]

Not suppose to be very complex.

Thanks!


RE: Unpacking nested lists - buran - Apr-14-2020

>>> foo = [[1,1],[1,3]] 
>>> [sum(item) for item in zip(*foo)]
[2, 4]
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> [sum(item) for item in zip(*foo)]
[2, 1, 101]
an alternative to list comprehension is map
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> list(map(sum, zip(*foo)))
[2, 1, 101]