The task of concatenate twolists of listsrow-wise, meaning we merge corresponding sublists into a single sublist.For example, given a = [[4, 3], [1, 2]] and b = [[7, 5], [9, 6]], we pair elements at the same index: [4, 3] froma is combined with [7, 5] from b, resulting in [4, 3, 7, 5], and [1, 2] froma merges with [9, 6] fromb, forming [1, 2, 9, 6]. The final output is [[4, 3, 7, 5], [1, 2, 9, 6]].
Using list comprehension with zip
List comprehension combined withzip() iterates through both lists simultaneously and concatenates corresponding sublists using the + operator. This method is concise and easy to read.
Pythona=[[4,3,5],[1,2,3],[3,7,4]]b=[[1,3],[9,3,5,7],[8]]a=[x+yforx,yinzip(a,b)]print(a)
Output[[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation: List comprehension with zip()pairs corresponding sublists from a and b, forming tuples. The + operator concatenates each pair (x, y), appending elements ofy tox, resulting in a new list of merged sublists.
Using map with zip
map() functionapplies a lambda functionto each pair of sublists returned by zip(), concatenating them using the + operator. This method is functional and avoids explicit loops.
Pythona=[[4,3,5],[1,2,3],[3,7,4]]b=[[1,3],[9,3,5,7],[8]]a=list(map(lambdax:x[0]+x[1],zip(a,b)))print(a)
Output[[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation: map() with zip()pairs corresponding sublists froma andb, merging each pair using + in a lambda function. The result is converted to a list of concatenated sublists.
Using a loop with extend
This method modifies the first lista in place by iterating over its elements and appending elements from the corresponding sublists inb using extend(). It is efficient when working with large datasets.
Pythona=[[4,3,5],[1,2,3],[3,7,4]]b=[[1,3],[9,3,5,7],[8]]foriinrange(len(a)):a[i].extend(b[i])print(a)
Output[[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation:This code iterates through a, using extend() to append corresponding sublists fromb, modifying a in place with merged sublists.
Using itertools.chain
chain() function from itertools flattens multiple iterables into a single iterable. Here, it is used inside a list comprehension to concatenate corresponding sublists.
Pythonfromitertoolsimportchaina=[[4,3,5],[1,2,3],[3,7,4]]b=[[1,3],[9,3,5,7],[8]]a=[list(chain(x,y))forx,yinzip(a,b)]print(a)
Output[[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]
Explanation: This code pairs sublists using zip(), merges them withchain() and converts the result into a list, forming concatenated sublists.