-2

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
jm_24
  • 11
  • 1
  • When you write `for x in list1`, `x` is the element, not the index. So you can't use `list1[x]`. – Barmar Aug 19 '22 at 01:30

4 Answers4

0

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']]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
-1

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

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)]
Ry-
  • 218,210
  • 55
  • 464
  • 476
-1

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']]
danPho
  • 87
  • 1
  • 6