Python | Merge two list of lists according to first element
Last Updated :
17 Apr, 2023
Given two list of lists of equal length, write a Python program to merge the given two lists, according to the first common element of each sublist.
Examples:
Input : lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]
lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]
Output : [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Input : lst1 = [ ['c', 'class'], ['g', 'greek'], ]
lst2 = [['c', 'coder'], ['g', 'god'], ]
Output : [['c', 'class', 'coder'], ['g', 'greek', 'god']]
Method #1: Python zip() with list comprehension
Python3
def merge(lst1, lst2):
return [a + [b[ 1 ]] for (a, b) in zip (lst1, lst2)]
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
print (merge(lst1, lst2))
|
Output:
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Time complexity: O(n), where n is the number of elements in the lists.
Auxiliary space: O(n), as a new list is created with the combined elements from both lists.
Method #2 : Python enumerate() with list comprehension
Python3
import collections
def merge(lst1, lst2):
return [(sub + [lst2[i][ - 1 ]]) for i, sub in enumerate (lst1)]
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
print (merge(lst1, lst2))
|
Output:
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Time complexity: O(n), where n is the length of lst1 or lst2 (whichever is smaller), as we are iterating through the lists only once.
Auxiliary space: O(n), where n is the length of lst1 or lst2 (whichever is smaller), as we are creating a new list of the same length.
Method #3: Python dictionary In this method, we initialize ‘dict1’ with collections.defaultdict and traverse through ‘lst1’+’lst2’ and append the first element of ‘lst1’ as key and tupled second element of both respective sublists as value. Finally, we traverse through ‘dict1’ and initialize ‘dictlist’ with the desired output.
Python3
import collections
def merge(lst1, lst2):
dict1 = collections.defaultdict( list )
for e in lst1 + lst2:
dict1[e[ 0 ]].append(e[ 1 ])
dictlist = list ()
for key, value in dict1.items():
dictlist.append([key] + value)
return dictlist
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
print (merge(lst1, lst2))
|
Output:
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Time complexity: O(n), where n is the total number of elements in lst1 and lst2.
Auxiliary space: O(n), where n is the total number of elements in lst1 and lst2.
Method #4: Using extend() and for loop
Python3
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
lst1.extend(lst2)
x = []
res = []
for i in lst1:
if i[ 0 ] not in x:
x.append(i[ 0 ])
for i in x:
p = []
p.append(i)
for j in lst1:
if (j[ 0 ] = = i):
p.append(j[ 1 ])
res.append(p)
print (res)
|
Output
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Time Complexity: O(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 list
Method #5: Using a list comprehension and a dictionary comprehension ( 2 lines ):
In the first line of the function, we initialize a dictionary called values with the values from the second list. We do this by using a dictionary comprehension, which is a concise way to create a dictionary from an iterable. The comprehension iterates through each sublist in lst2 and stores the first element as the key and the second element as the value.
In the second line, we use a list comprehension to iterate through each sublist in lst1 and merge it with the corresponding values in values. The comprehension checks if the first element of the sublist is in values using the in keyword. If it is, it creates a new list with the first element of the sublist, the second element of the sublist, and the value from values that corresponds to the first element. If the first element is not in values, the sublist is not included in the merged list.
Python3
def merge(lst1, lst2):
values = {l[ 0 ]: l[ 1 ] for l in lst2}
return [[l[ 0 ]] + [l[ 1 ]] + [values[l[ 0 ]]] for l in lst1 if l[ 0 ] in values]
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
print (merge(lst1, lst2))
|
Output
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Tme complexity: O(n), where n is the length of the lists, since we are iterating through both lists once.
Auxiliary space: O(n), since we are storing the values from the second list in a dictionary.
Method #6: Using a for loop and a dictionary
Step-by-step approach:
- Create an empty dictionary merged_dict
- Traverse through the lists lst1 and lst2 using a for loop
- For each iteration, get the first element of the sublist and check if it already exists as a key in the merged_dict
- If it does not exist, create a new key with the first element of the sublist as the key and the second element as the value in a list format
- If it does exist, append the second element of the current sublist to the list associated with the existing key
- After the for loop, create a list merged_list that will contain the merged sublists based on the keys in the merged_dict
- Traverse through the keys in the merged_dict and append a new list to merged_list with the current key and the associated list of values
- Return the merged_list as the final output
Below is the implementation of the above approach:
Python3
def merge(lst1, lst2):
merged_dict = {}
for sublist in lst1 + lst2:
if sublist[ 0 ] not in merged_dict:
merged_dict[sublist[ 0 ]] = [sublist[ 1 ]]
else :
merged_dict[sublist[ 0 ]].append(sublist[ 1 ])
merged_list = []
for key in merged_dict:
merged_list.append([key] + merged_dict[key])
return merged_list
lst1 = [[ 1 , 'Alice' ], [ 2 , 'Bob' ], [ 3 , 'Cara' ]]
lst2 = [[ 1 , 'Delhi' ], [ 2 , 'Mumbai' ], [ 3 , 'Chennai' ]]
print (merge(lst1, lst2))
|
Output
[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]
Time complexity: O(n), where n is the length of the input lists
Auxiliary space: O(n), where n is the length of the input lists, for creating the dictionary and merged list
Similar Reads
Python | Merge two lists into list of tuples
The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
3 min read
Move One List Element to Another List - Python
The task of moving one list element to another in Python involves locating a specific element in the source list, removing it, and inserting it into the target list at a desired position. For example, if a = [4, 5, 6, 7, 3, 8] and b = [7, 6, 3, 8, 10, 12], moving 10 from b to index 4 in a results in
3 min read
Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have: a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The output should be: [{1, 2}, {1, 2, 3}, {2}, {0}] Let's explore some method's t
2 min read
Python | Merge first and last elements separately in a list
Given a list of lists, where each sublist consists of only two elements, write a Python program to merge the first and last element of each sublist separately and finally, output a list of two sub-lists, one containing all first elements and other containing all last elements. Examples: Input : [['x
2 min read
Python | Convert List of lists to list of Strings
Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
4 min read
Python - Combine list with other list elements
Given two lists, combine list with each element of the other list. Examples: Input : test_list = [3, 5, 7], pair_list = ['Gfg', 'is', 'best'] Output : [([3, 5, 7], 'Gfg'), ([3, 5, 7], 'is'), ([3, 5, 7], 'best')] Explanation : All lists paired with each element from other list. Input : test_list = [3
6 min read
Python | Find common elements in list of lists
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
6 min read
Sorting List of Lists with First Element of Each Sub-List in Python
In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list o
3 min read
How to Zip two lists of lists in Python?
zip() function typically aggregates values from containers. However, there are cases where we need to merge multiple lists of lists. In this article, we will explore various efficient approaches to Zip two lists of lists in Python. List Comprehension provides a concise way to zip two lists of lists
3 min read
Python - Filter unequal elements of two lists corresponding same index
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using
5 min read