I have two lists of lists that have equivalent numbers of items. The two lists look like this:
L1 = [[1, 2], [3, 4], [5, 6]]
L2 =[[a, b], [c, d], [e, f]]
I am looking to create one list that looks like this:
Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]]
I was attempting to use zip()
something like this:
for list1, list2 in zip(*L1, *L2):
Lmerge = [list1, list2]
What is the best way to combine two lists of lists? Thanks in advance.
Or,
or,
We can also do it without
zip()
:Some benchmarks
Here are some benchmarks for the answers provided so far.
It looks like the most popular answer (
[x + y for x,y in zip(L1,L2)]
) is pretty much on par with @hammar'smap
solution.On the other hand, the alternative solutions I've given have proven to be rubbish!However, the fastest solutions (for now) seems to be the ones that uses list comprehension without
zip()
.@Zac's suggestion is really quick, but then we're comparing apples and oranges here since it does a list extension in-place on
L1
instead of creating a third list. So, ifL1
is not longer needed, this is a great solution.However, if
L1
has to be kept intact, then performance would be sub par once you include the deepcopy.You want to combine the sublists with the plus operator, and iterate over them in a list comprehension: