Open In App

Python | Merge corresponding sublists from two different lists

Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists containing sublists, write a Python program to merge the two sublists based on same index. 

Examples:

Input : l1 = [['+', '-', '+'], ['-', '+'], ['+', '-', '+']]
        l2 = [['2a3', 'b2', '3c'], ['a3', 'b2'], ['a3', '2b2', '5c']]
Output : [['+2a3', '-b2', '+3c'], ['-a3', '+b2'], ['+a3', '-2b2', '+5c']]

Input : l1 = [['1', '2'], ['1', '2', '3']]
        l2 = [['anne', 'bob'], ['cara', 'drake', 'ezra']]
Output : [['1anne', '2bob'], ['1cara', '2drake', '3ezra']]

Approach #1: List comprehension with zip() We can use nested list comprehension with zip() function. The zip() function take iterables, makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples. Now traversing through the zipped tuples using two variable i and j, it concatenates both the variables using ‘+’ operator. 

Python3




# Python3 code to Concatenate
# corresponding sublists from two
# different lists
 
def concatList(l1, l2):
    return [[i + j for i, j in zip(x, y)]
                 for x, y in zip(l1, l2)]
     
# Driver Code
l1 = [['1', '2'], ['1', '2', '3']]
l2 = [['anne', 'bob'], ['cara', 'drake', 'ezra']]
print(concatList(l1, l2))


Output:

[['1anne', '2bob'], ['1cara', '2drake', '3ezra']]

Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list 

Approach #2: list comprehension with map() Instead of the nested list comprehension we can use the function map() with the operator concat. We traverse through zipped list1 and list2 using variable i and j. Then we apply concat operator on i and j to concatenate them. 

Python3




# Python3 code to Concatenate
# corresponding sublists from two
# different lists
from operator import concat
 
def concatList(l1, l2):
    return [list(map(concat, i, j)) for i, j in zip(l1, l2)]
     
# Driver Code
l1 = [['1', '2'], ['1', '2', '3']]
l2 = [['anne', 'bob'], ['cara', 'drake', 'ezra']]
print(concatList(l1, l2))


Output:

[['1anne', '2bob'], ['1cara', '2drake', '3ezra']]

Approach #3: Using the map function and lambda

Using the map function: You could use the map function to apply a lambda function to each element in the sublists and merge them. This approach has a time complexity of O(n) where n is the number of elements in the lists and space complexity of O(n)

Python3




def concat_lists(l1, l2):
    return [list(map(lambda x, y: x + y, x, y)) for x, y in zip(l1, l2)]
 
l1 = [['1', '2'], ['1', '2', '3']]
l2 = [['anne', 'bob'], ['cara', 'drake', 'ezra']]
print(concat_lists(l1, l2))  # Output: [['1anne', '2bob'], ['1cara', '2drake', '3ezra']]
#This code is contributed by Edula Vinay Kumar Reddy


Output

[['1anne', '2bob'], ['1cara', '2drake', '3ezra']]

Method 4: using a for loop with enumerate():

Step-by-step approach:

  • Define a function named concatList which takes two lists as arguments.
  • Create an empty list named result.
  • Use a for loop to iterate through each sublist in l1, along with its index.
  • For each sublist, use zip() to iterate through its elements along with the corresponding elements from the same index sublist in l2.
  • Append the concatenated sublists to the result list.
  • Return the result list.

Below is the implementation of the above approach:

Python3




# Define a function named concatList which takes two lists as arguments.
def concatList(l1, l2):
    # Create an empty list named result to store the concatenated sublists.
    result = []
    # Use a for loop to iterate through each sublist in l1, along with its index.
    for index, sublist in enumerate(l1):
        # Create a new list named concat to store the concatenated elements.
        concat = []
        # Use zip() to iterate through each element of the current sublist along with the corresponding element in the same index sublist of l2.
        for elem1, elem2 in zip(sublist, l2[index]):
            # Append the concatenated string to the concat list.
            concat.append(elem1 + elem2)
        # Append the concatenated sublist to the result list.
        result.append(concat)
    # Return the result list.
    return result
 
# Define two lists named l1 and l2.
l1 = [['1', '2'], ['1', '2', '3']]
l2 = [['anne', 'bob'], ['cara', 'drake', 'ezra']]
 
# Call the concatList function with l1 and l2 as arguments and print the result.
print(concatList(l1, l2))


Output

[['1anne', '2bob'], ['1cara', '2drake', '3ezra']]

Time complexity: O(n^2), where n is the length of the longest sublist in l1 or l2. This is because we need to iterate through each element of the longest sublist in both lists.
Auxiliary space: O(n), where n is the length of the longest sublist in l1 or l2. This is because we need to create a new list to store the concatenated sublists.

Approach #5: Using list comprehension and string formatting

In this approach, we can use a list comprehension to loop through both the lists at the same time and concatenate the elements using string formatting.

Algorithm:

Define a function named concatList that takes two lists as arguments.
Use a list comprehension to loop through both the lists simultaneously using the zip function.
Inside the list comprehension, use string formatting to concatenate the elements of each sublist at the same index.
Return the resulting list.
 

Python3




def concatList(l1, l2):
    # Use a list comprehension to loop through both the lists simultaneously using the zip function.
    result = [ [f"{x}{y}" for x,y in zip(sublist1, sublist2)] for sublist1, sublist2 in zip(l1, l2)]
    return result
 
# Example usage:
l1 = [['+', '-', '+'], ['-', '+'], ['+', '-', '+']]
l2 = [['2a3', 'b2', '3c'], ['a3', 'b2'], ['a3', '2b2', '5c']]
print(concatList(l1, l2))
 
# Output: [['+2a3', '-b2', '+3c'], ['-a3', '+b2'], ['+a3', '-2b2', '+5c']]


Output

[['+2a3', '-b2', '+3c'], ['-a3', '+b2'], ['+a3', '-2b2', '+5c']]

Time complexity: O(n), where n is the total number of elements in both the lists.
Auxiliary Space: O(n), since we are creating a new list with the same number of elements as the input lists.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads