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])
CodePudding user response:
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]]
CodePudding user response:
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]]
CodePudding user response:
for el1, el2 in zip(a, b):
el1.extend(el2)
CodePudding user response:
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]
CodePudding user response:
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]]