lynnisjoyce
lynnisjoyce

Reputation: 3

Copy values from one nested list into another empty nested list

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?

Upvotes: 0

Views: 328

Answers (4)

brechmos
brechmos

Reputation: 1316

The other way you to do it is using a list comprehension:

L = [[1], [2.718], [3.14], [4]]
M = [[], [2], [3], []]

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

print(M)

Same idea as above...

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

Using zip with list-comprehension

[j if j else i for i,j in zip(L,M)]
#[[1], [2], [3], [4]]

Upvotes: 0

When doing:

for i in M:

The value of i will always be the value of the array in a given location.

You want the actual index, so loop through a range from 0 to the length of the index.

for i in range(0, len(M)):
    if len(M[i]) == 0:
        M[i] = L[i]

Upvotes: 0

bnaecker
bnaecker

Reputation: 6440

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.

Upvotes: 1

Related Questions