Merging two nested lists based on the index in Python

Hello my question has two parts.

First part : how to merge two nested lists based on the index , for example :

L1 = [[1,2],[4,5]]
L2 = [[11,22],[44,55]]

I want to merge the above nested lists based on their index so that i get an output like :

L3 = [ [[1,11],[2,22]] , [[4,44],[5,55]] ]

The second part of the problem is to add a constant value to all the nested lists so that the output is :

L3 = [ [[1,11,0],[2,22,0]] , [[4,44,0],[5,55,0]] ]

>Solution :

You can use a nested list comprehension with zip for both requirements:

>>> [[list(x) for x in zip(*t)] for t in zip(L1, L2)]
[[[1, 11], [2, 22]], [[4, 44], [5, 55]]]

and

>>> [[[a, b, 0] for a, b in zip(*t)] for t in zip(L1, L2)]
[[[1, 11, 0], [2, 22, 0]], [[4, 44, 0], [5, 55, 0]]]

Leave a Reply