Reputation: 307
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
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
Reputation: 160647
Or, a comprehension with unpacking, after zip
ing, 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
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