Python | Merge elements of sublists
Last Updated :
18 Apr, 2023
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
Python3
list1 = [[ 1 , 20 , 30 ],
[ 40 , 29 , 72 ],
[ 119 , 123 , 115 ]]
list2 = [[ 29 , 57 , 64 , 22 ],
[ 33 , 66 , 88 , 15 ],
[ 121 , 100 , 15 , 117 ]]
Output = list ( map ( lambda x, y:x + y, list1, list2))
print (Output)
|
Output:
[[1, 20, 30, 29, 57, 64, 22],
[40, 29, 72, 33, 66, 88, 15],
[119, 123, 115, 121, 100, 15, 117]]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using Zip()
Python3
list1 = [[ 1 , 20 , 30 ],
[ 40 , 29 , 72 ],
[ 119 , 123 , 115 ]]
list2 = [[ 29 , 57 , 64 , 22 ],
[ 33 , 66 , 88 , 15 ],
[ 121 , 100 , 15 , 117 ]]
Output = [x + y for x, y in zip (list1, list2)]
print (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()
Python3
from operator import concat
from itertools import starmap
list1 = [[ 1 , 20 , 30 ],
[ 40 , 29 , 72 ],
[ 119 , 123 , 115 ]]
list2 = [[ 29 , 57 , 64 , 22 ],
[ 33 , 66 , 88 , 15 ],
[ 121 , 100 , 15 , 117 ]]
Output = list (starmap(concat, zip (list1, list2)))
print (Output)
|
Output:
[[1, 20, 30, 29, 57, 64, 22],
[40, 29, 72, 33, 66, 88, 15],
[119, 123, 115, 121, 100, 15, 117]]
Method #4: Using inbuilt extend()
This code uses the zip function to iterate through list1 and list2 simultaneously. For each sublist in list1 and list2, it uses the extend method to add the elements of sublist2 to sublist1. The modified sublist1 is then appended to merged_list.
Python3
list1 = [[ 1 , 20 , 30 ],
[ 40 , 29 , 72 ],
[ 119 , 123 , 115 ]]
list2 = [[ 29 , 57 , 64 , 22 ],
[ 33 , 66 , 88 , 15 ],
[ 121 , 100 , 15 , 117 ]]
merged_list = []
for sublist1, sublist2 in zip (list1, list2):
sublist1.extend(sublist2)
merged_list.append(sublist1)
print (merged_list)
|
Output
[[1, 20, 30, 29, 57, 64, 22], [40, 29, 72, 33, 66, 88, 15], [119, 123, 115, 121, 100, 15, 117]]
The time complexity of this code is O(n), where n is the total number of elements in list1 and list2. The space complexity is also O(n), as the merged_list will also have n elements.
Share your thoughts in the comments
Please Login to comment...