Python | Merge elements of sublists
Given two lists containing sublists, the task is to merge elements of sublist of two lists in a single list.
Examples:
Input:
list1 = [[1, 20, 30],
[40, 29, 72],
[119, 123, 115]]
list2 = [[29, 57, 64, 22],
[33, 66, 88, 15],
[121, 100, 15, 117]]
Output: [[1, 20, 30, 29, 57, 64, 22],
[40, 29, 72, 33, 66, 88, 15],
[119, 123, 115, 121, 100, 15, 117]]
Method #1: Using Map + lambda
# Python code to merge elements of sublists # Initialisation of first listlist1 = [[1, 20, 30], [40, 29, 72], [119, 123, 115]] # Initialisation of second listlist2 = [[29, 57, 64, 22], [33, 66, 88, 15], [121, 100, 15, 117]] # Using map + lambda to merge listsOutput = list(map(lambda x, y:x + y, list1, list2)) # Printing outputprint(Output) |
Output:
[[1, 20, 30, 29, 57, 64, 22], [40, 29, 72, 33, 66, 88, 15], [119, 123, 115, 121, 100, 15, 117]]
Method #2: Using Zip()
# Python code to merge elements of sublists # Initialisation of first listlist1 = [[1, 20, 30], [40, 29, 72], [119, 123, 115]] # Initialisation of second listlist2 = [[29, 57, 64, 22], [33, 66, 88, 15], [121, 100, 15, 117]] # Using zip to merge listsOutput = [x + y for x, y in zip(list1, list2)] # Printing outputprint(Output) |
Output:
[[1, 20, 30, 29, 57, 64, 22], [40, 29, 72, 33, 66, 88, 15], [119, 123, 115, 121, 100, 15, 117]]
Method #3: Using starmap() and concat()
# Python code to merge elements of sublists from operator import concatfrom itertools import starmap # Initialisation of first listlist1 = [[1, 20, 30], [40, 29, 72], [119, 123, 115]] # Initialisation of second listlist2 = [[29, 57, 64, 22], [33, 66, 88, 15], [121, 100, 15, 117]] # Using starmap() and concat to merge listOutput = list(starmap(concat, zip(list1, list2))) # Printing outputprint(Output) |
Output:
[[1, 20, 30, 29, 57, 64, 22], [40, 29, 72, 33, 66, 88, 15], [119, 123, 115, 121, 100, 15, 117]]


