Copy values from one nested list into another empty nested list

Keywords: python nested-lists

Question: 

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:

M[0].append(L[0][0])
M[3].append(L[3][0]) 

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: 
        M[i].append(L[i][0])

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?

Answers: 

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.