Extending lists of lists

Question:

I’m trying to extend two lists of lists in python, so that item 1 of the first list of lists extends with item 1 of the second list of lists, and so forth.
I’m new to this and self-taught, so could be missing something very simple, but I can’t find an answer anywhere.
This is what I feel the code should be, but obviously not working.

list1[x].extend(list2[x]) for x in list1

What I’m trying to achieve is this:

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [[a,b,c],[d,e,f],[g,h,i]]

output = [[1,2,3,a,b,c],[4,5,6,d,e,f],[7,8,9,g,h,i]]

Any ideas?

Asked By: jm_24

||

Answers:

You can use zip:

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [['a','b','c'], ['d','e','f'], ['g','h','i']]

output = [sub1 + sub2 for sub1, sub2 in zip(list1, list2)]

print(output)
# [[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]
Answered By: j1-lee

Use zip() to loop over the two lists in parallel. Then use extend() to append the sublist from list2 to the corresponding sublist in list1.

for l1, l2 in zip(list1, list2):
    l1.extend(l2)
print(list1)
Answered By: Barmar

list1[x].extend(list2[x]) does achieve the result you want for one pair of lists, if list1[x] is [1, 2, 3] and list2[x] is [a, b, c], for example.

That means x has to be an index:

x = 0
list1[x].extend(list2[x])
# now the first list in `list1` looks like your desired output

To do that for every pair of lists, loop over all possible indexes xrange(upper) is the range of integers from 0 (inclusive) to upper (exclusive):

for x in range(len(list1)):
    list1[x].extend(list2[x])

# now `list1` contains your output

To produce a new list of lists instead of altering the lists in list1, you can concatenate lists with the + operator instead:

>>> [1, 2, 3] + ['a', 'b', 'c']
[1, 2, 3, 'a', 'b', 'c']
output = []

for x in range(len(list1)):
    output.append(list1[x] + list2[x])

And finally, the idiomatic Python for this that you’ll get around to someday is:

output = [x1 + x2 for x1, x2 in zip(list1, list2)]
Answered By: Ry-

I have simply used list comprehension with list addition, while zipping the correlated lists together

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [['a','b','c'], ['d','e','f'], ['g','h','i']]

list3 = [l1+l2 for l1, l2 in zip(list1, list2)]
print(list3)

[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]
Answered By: danPho
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.