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:
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]]