How can I append two list with eachother?

Viewed 66

I have two lists and I want to append one with another, like this:

a = [['bmw'], ['audi'], ['benz'], ['honda']]
b = [[12,2], [3,4], [7,5], [6,23]]

new list should be like this:

n = [['bmw', 12, 2], ['audi', 3, 4], ['benz', 7, 5], ['honda', 6, 23]]

I try this but it didn't work:

for i, j in a, b:
    a[i].append(b[j])
6 Answers

Use list comprehension:

[i+j for i,j in zip(a, b)]

Results in:

[['bmw', 12, 2], ['audi', 3, 4], ['benz', 7, 5], ['honda', 6, 23]]

You almost got it right, you should use extend instead of append:

a = [['bmw'], ['audi'], ['benz'], ['honda']]
b = [[12,2], [3,4], [7,5], [6,23]]

for i, j in zip(a, b):
    i.extend(j)

print(a)

Output:

[['bmw', 12, 2], ['audi', 3, 4], ['benz', 7, 5], ['honda', 6, 23]]
for el1, el2 in zip(a, b):
  el1.extend(el2)

You can use zip and concatenation:

a = [['bmw'], ['audi'], ['benz'], ['honda']]
b = [[12,2], [3,4], [7,5], [6,23]]
c = [item[0] + item[1] for item in zip(a, b)]

Which yields:

['bmw', 12, 2]
['audi', 3, 4]
['benz', 7, 5]
['honda', 6, 23]

You can use list comprehension:

result = [a[i] + b[i] for i in range(len(a))] 

Results in:

[['bmw', 12, 2], ['audi', 3, 4], ['benz', 7, 5], ['honda', 6, 23]]

Using map() & lambda function, * unpacking to a list and + list concatenation:

res = [*map(lambda x, y: x + y, a, b)]
print(res)
Related