Copy values from one nested list into another empty nested list

Keywords: python nested-lists


I would like to move a value inside one nested list into another empty nested list. More specifically, I'd like copy the value if and only if the nested list with the same index is empty.

If I have:

L = [[1], [2.718], [3.14], [4]]

M = [[], [2], [3], []]

I want to return:

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

I know that I can do each one by hand by doing:


but I'd like to do it with a for loop for lists that are much bigger.

I've tried doing

for i in M:
    if bool(i)==False: 

But this gives me "TypeError: list indices must be integers, not list" for the last line. Any ideas on how to fix the for loop?


You can iterate over the lists in tandem like so:

for l, m in zip(L, M):
    if len(m) == 0:
        m[:] = l[:]

The slicing at the end will ensure that you copy the object inside the resulting sublist of M.