ponderwonder
ponderwonder

Reputation: 127

How to make a combination of a nested list and a list?

I want to combine a nested list with another list.

a = [['a_1','b_2','c_3'],['a_3','b_4','c_5']]
b = ['d_1','d_2']

The goal is to append each element of list b to each sublist of list a.

c = [['a_1', 'b_2', 'c_3', 'd_1'], ['a_3', 'b_4', 'c_5', 'd_1'], ['a_1', 'b_2', 'c_3', 'd_2'], ['a_3', 'b_4', 'c_5','d_2']]

Any ideas? Many thanks!

Upvotes: 1

Views: 59

Answers (3)

Ritesh Bhartiya
Ritesh Bhartiya

Reputation: 51

a[0].append(b[0])
a[1].append(b[1])

Or for many lists in a:

for i in range(len(a)):
    a[i].append(b[i])

Upvotes: 0

Yappi
Yappi

Reputation: 43

You can iterate the first list and append the members of the second list to the members of the first. You can try this code,

c=[]
for i in b:
    for j in a:
        j.append(i)
        c.append(j)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195613

a = [['a_1','b_2','c_3'],['a_3','b_4','c_5']]
b = ['d_1','d_2']

out = [[*l2, l1] for l1 in b for l2 in a]
print(out)

Prints:

[['a_1', 'b_2', 'c_3', 'd_1'], ['a_3', 'b_4', 'c_5', 'd_1'], ['a_1', 'b_2', 'c_3', 'd_2'], ['a_3', 'b_4', 'c_5', 'd_2']]

Upvotes: 5

Related Questions