Alduno
Alduno

Reputation: 307

Append list elements to list of lists in python

Given the following lists:

list1 = [[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]]
list2 = [10, 11, 12, 13]

What is the best way to change list1 so it becomes the following list in python?

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

Upvotes: 2

Views: 5089

Answers (3)

PythonProgrammi
PythonProgrammi

Reputation: 23463

You can make it this way:

list1 = [[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]]
list2 = [10, 11, 12, 13]

def add_item_to_list_of_lists(list11, list2):
    # list1, list to add item of the second list to
    # list2, list with items to add to the first one
    for numlist, each_list in enumerate(list1):
        each_list.append(list2[numlist])

add_item_to_list_of_lists(list1, list2)
print(list1)

Output

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

Upvotes: -1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160647

Or, a comprehension with unpacking, after ziping, if you're using Python >= 3.5:

>>> l = [[*i, j] for i,j in zip(list1, list2)]
>>> print(l)
[[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

Of course, if the list sizes might differ, you'd be better off using zip_longest from itertools to gracefully handle the extra elements.

Upvotes: 5

akuiper
akuiper

Reputation: 215117

You can use zip:

[x + [y] for x, y in zip(list1, list2)]
# [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

To modify list1 in place, you could do:

for x, y in zip(list1, list2):
    x.append(y)

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

Upvotes: 9

Related Questions