-4

Let's say I have:

A = [[a,b,c,d],[1,2,3,4]]
B = [[1.2,1.7],[1.6,1.8]]

I want to combine 2 list to one list

C = [[a,b,c,d,1.2,1.7],[1,2,3,4,1.6,1.8]]

How can I do that in Python? Thanks

smithchao
  • 3
  • 1

3 Answers3

0

Use extend() method to concatenate the elements of one list to another and then append this resulting list to the final list.

for i in range(len(a)):
    a[i].extend(b[i])
    c.append(a[i])
Gautham M
  • 4,816
  • 3
  • 15
  • 37
  • 1
    While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – hellow Nov 09 '18 at 09:45
0

There are lot's of different ways of combining two lists.

You can add two lists together:

[1,2,3] + [4,5,6]

Will give you:

[1,2,3,4,5,6]

You can append a list to a list of lists:

[[1,2,3],[4,5,6]].append([7,8,9])

Will give you:

[[1,2,3],[4,5,6],[7,8,9]]

You can zip two lists as well:

zip([1,2,3],[4,5,6])

Will give you:

[(1,4),(2,5),(3,6)]

What it looks like you're looking for is:

C = []

for sublist_1, sublist_2 in zip(A, B):
    C.append(sublist_1 + sublist_2)

Or more compactly using list comprehension:

C = [sublist_1 + sublist_2 for sublist_2, sublist_2 in zip(A,B)]
Neil
  • 3,020
  • 4
  • 25
  • 48
0

You can use zip and itertools.starmap for this

In [110]: A
Out[110]: [[2, 4, 5, 6], [1, 2, 3, 4]]

In [111]: B
Out[111]: [[1.2, 1.7], [1.6, 1.8]]

In [112]: import itertools

In [113]: list(itertools.starmap(lambda x,y:x+y,zip(A,B)))
Out[113]: [[2, 4, 5, 6, 1.2, 1.7], [1, 2, 3, 4, 1.6, 1.8]]
Albin Paul
  • 3,330
  • 2
  • 14
  • 30