2

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]]

3 Answers 3

9

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]]
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

-1

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]]

2 Comments

Why are you providing mutable default args? Are their contents supposed to be comments instead?
Why are you using list1[numlist] instead of each_list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.