Python – How to insert different values from different lists into a specific list

How to insert different values from different lists into a specific list… here is a solution to the problem.

How to insert different values from different lists into a specific list

I have a list

a = [[1,2,3],[3,4,5]]

In each last row, I want to insert values from different lists

b=[6,7]

The result I want is

[[1,2,3,6],[3,4,5,7]]

I’m using:

for i in range (0,len(a)):
    for j in range (0,len(b)):
        if j==0:
            a[i].append(b[j])
            m.append(a[i])
        else:
            a[i][3]=b[j]
            m.append(a[i])
        print m

But I didn’t get the expected results. This gave me:

[[1, 2, 3, 7], [1, 2, 3, 7], [3, 4, 5, 7], [3, 4, 5, 7]]

Can anyone help me figure out the right code snippet.

Solution

This is a solution using zip:

result = [sublist_a + [el_b] for sublist_a, el_b in zip(a, b)]

It gives the expected output:

[[1, 2, 3, 6], [3, 4, 5, 7]]

Related Problems and Solutions