Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can we add two different nested lists together?

if we have a nested list ListA and another nested list ListB of same length how can we add these nested lists replacing original values of ListA in Python? I browsed on hours on end, and found no reliable solution.

Would it be possible to do inside a for loop too? Optimally without NumPy, pure python.

Here’s a pseudo code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ListA = [[1, 2], [3, 4]]

ListB = [[5, 6], [7, 8]]

Expected output: ListA = [[6, 8], [10, 12]]

because… 1 + 5, 2 + 8 etc…

>Solution :

You can use list comprehension with zip:

ListA = [[1, 2], [3, 4]]
ListB = [[5, 6], [7, 8]]

output = [[x + y for x, y in zip(sublstA, sublstB)] for sublstA, sublstB in zip(ListA, ListB)]
print(output) # [[6, 8], [10, 12]]

Slight generalization:

ListA = [[1, 2, 0], [3, 4]]
ListB = [[5, 6, 1], [7, 8]]
ListC = [[9, 0, 2], [1, 2]]

output = [[sum(nums) for nums in zip(*sublists)] for sublists in zip(ListA, ListB, ListC)]
print(output) # [[15, 8, 3], [11, 14]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading