ColleenB
ColleenB

Reputation: 175

How to add a list to a list of list

I am trying to combine two lists. This is what i have

l1 = [[1,2,3], [3,4,5], [10, 11, 12]]
l2 = [6,7,8]

This is what I have tried this

def merge(list1, list2):
    merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]
    return merged_list

This produces something close

l3 = merge(l1,l2)
[([1, 2, 3], 6), ([3, 4, 5], 7), ([10, 11, 12], 8)]

But this is what I want

l3 = [1,2,3,6], [3,4,5,7], [10,11,12,8]

How do i merge the two lists to get the list of list above?

Upvotes: 2

Views: 1310

Answers (4)

Swati Srivastava
Swati Srivastava

Reputation: 1157

for i in range(len(l1)):
    l1[i].append(l2[i])

Simply add the ith element of l2 in ith list of l1. This gives the output

[[1, 2, 3, 6], [3, 4, 5, 7], [10, 11, 12, 8]]

Upvotes: 0

Sebastien D
Sebastien D

Reputation: 4482

With a simple list of comprehension:

l1 = [[1,2,3], [3,4,5], [10, 11, 12]]
l2 = [6,7,8]

[l1[idx] + [val] for idx, val in enumerate(l2)]

Ouptut

[[1, 2, 3, 6], [3, 4, 5, 7], [10, 11, 12, 8]]

Upvotes: 1

Ajay Verma
Ajay Verma

Reputation: 630

I suggest making a copy of l1 before proceeding

l1 = [[1,2,3], [3,4,5], [10, 11, 12]]
l2 = [6,7,8]
for i, j in zip(l1,l2):
    i.append(j)
print(l1)

Output:

[[1, 2, 3, 6], [3, 4, 5, 7], [10, 11, 12, 8]]

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Use zip with + operator to append

Ex:

l1 = [[1,2,3], [3,4,5], [10, 11, 12]]
l2 = [6,7,8]


def merge(list1, list2):
    return [i + [v] for i, v in zip(list1, list2)]
print( merge(l1,l2))
# --> [[1, 2, 3, 6], [3, 4, 5, 7], [10, 11, 12, 8]]

Upvotes: 1

Related Questions