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
# Python3 program to Merge two list of
# lists according to first element
def merge(lst1, lst2):
return [a + [b[1]] for (a, b) in zip(lst1, lst2)]
# Driver code
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
# Python3 program to Merge two list of
# lists according to first element
import collections
def merge(lst1, lst2):
return [(sub + [lst2[i][-1]]) for i, sub in enumerate(lst1)]
# Driver code
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
# Python3 program to Merge two list of
# lists according to first element
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
# Driver code
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
# Python3 program to Merge two list of
# lists according to first element
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):
# Initialize a dictionary to store the values from the second list
values = {l[0]: l[1] for l in lst2}
# Use a list comprehension to merge the lists
return [[l[0]] + [l[1]] + [values[l[0]]] for l in lst1 if l[0] in values]
# Driver code
lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]
lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]
print(merge(lst1, lst2))
#This code is contributed by Edula Vinay Kumar Reddy
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
# Driver code
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 | Filter tuples according to list element presence
Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let's discuss certain ways in which this task can be performed.
8 min read
Merge Two Lists into List of Tuples - Python
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
Add Elements of Two Lists in Python
Adding corresponding elements of two lists can be useful in various situations such as processing sensor data, combining multiple sets of results, or performing element-wise operations in scientific computing. List Comprehension allows us to perform the addition in one line of code. It provides us a
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 to ac
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 : [['
2 min read
Python - Sort list according to other list order
Sorting a list based on the order defined by another list is a common requirement in Python, especially in scenarios involving custom sorting logic. This ensures that elements in the first list appear in the exact order specified in the second list. Python provides various methods to accomplish this
2 min read
Python Program to Merge a Matrix By the Elements of First Column
Given a Matrix, perform merge on the basis of the element in the first column. Input : test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"], [4, "cs"], [3, "best"]] Output : [[4, 'geeks', 'CS', 'cs'], [3, 'Gfg', 'best']] Explanation : 4 is paired with geeks, CS and cs hence are merged into 1 row. Input
5 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