Open In App

Python | Merge two lists into list of tuples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given two lists, write a Python program to merge the two lists into list of tuples. 

Examples:

Input : list1 = [1, 2, 3]
        list2 = ['a', 'b', 'c']
Output : [(1, 'a'), (2, 'b'), (3, 'c')]

Input : list1 = [1, 2, 3, 4]
        list2 = [ 1, 4, 9]
Output : [(1, 1), (2, 4), (3, 9), (4, '')]

Approach #1: Naive 

Here we will merge both the list into a list of tuples using a for loop. But the drawback is given two lists need to be of the same length.

Python3




def merge(list1, list2):
 
    merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]
     
    return merged_list
 
 
# Driver code
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print(merge(list1, list2))


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

Time complexity: O(n), where n is the length of the lists.
Auxiliary space: O(n)

Approach #2: Naive but more efficient 

This method remove the above-given drawback and work well with uneven lengths of the two lists. It also provides try catch error for Index error. 

Python3




def merge(list1, list2):
 
    merged_list = []
 
    for i in range(max((len(list1), len(list2)))):
 
        while True:
 
            try:
                tup = (list1[i], list2[i])
 
            except IndexError:
                if len(list1) & gt
                len(list2):
                    list2.append('')
                    tup = (list1[i], list2[i])
                elif len(list1) & lt
                len(list2):
                    list1.append('')
                    tup = (list1[i], list2[i])
                continue
 
            merged_list.append(tup)
            break
    return merged_list
 
 
# Input
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
 
# Print the answer
print(merge(list1, list2))


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

Time complexity: O(n) where n is the length of the longer list. This is because the code iterates through the length of the longer list (i.e., max(len(list1), len(list2))) and performs constant time operations in each iteration.
Auxiliary space: O(n) as well, where n is the length of the longer list. This is because the code creates a new list merged_list which stores tuples of elements from list1 and list2, and the size of this list would be equal to the length of the longer list.

Approach #3: Using zip() using zip() method to merge the two list elements and then typecasting into tuple. 

Python3




def merge(list1, list2):
 
    merged_list = tuple(zip(list1, list2))
    return merged_list
 
  # Input lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
 
# Print the answer
print(merge(list1, list2))


Output:

((1, 'a'), (2, 'b'), (3, 'c'))

Approach #4 : Using enumerate(), alternative to zip(). This method uses two for loops to enumerate through lists and merge the two lists.

Python3




def merge(list1, list2):
     
    merged_list = [(p1, p2) for idx1, p1 in enumerate(list1)
    for idx2, p2 in enumerate(list2) if idx1 == idx2]
    return merged_list
     
# Driver code
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print(merge(list1, list2))


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

Approach #5: Using map() and lambda. 

Python3




# Using map() and lambda
def listOfTuples(l1, l2):
    return list(map(lambda x, y:(x,y), l1, l2))
 
# Driver Code
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
 
print(listOfTuples(list1, list2))


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

 Approach #6:  Using a dictionary to merge the two lists.

First, create a dictionary where the keys are the elements from the first list and the values are the elements from the second list. Then, use the items() method on the dictionary to retrieve a list of tuples, each tuple containing a key-value pair from the dictionary.

Here is an example of this approach:

Python3




def merge(list1, list2):
    # Create a dictionary where the keys are the elements from list1 and the values are the elements from list2
    dict_ = {list1[i]: list2[i] for i in range(min(len(list1), len(list2)))}
     
    # Use the items() method on the dictionary to retrieve a list of tuples
    merged_list = list(dict_.items())
     
    return merged_list
 
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print(merge(list1, list2))
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

[(1, 'a'), (2, 'b'), (3, 'c')]

Time complexity: O(n)
Auxiliary Space: O(n)

 Approach #7:  Using Numpy

Algorithm:

  1. Determine the smaller size between list1 and list2.
  2. Slice the arrays of list1 and list2 from the beginning till the smaller size determined in step 1.
  3. Stack the sliced arrays horizontally to create a new 2D array.
  4. Determine which list is longer and add the remaining sliced elements from that list to the end of the resulting 2D array with an empty string.
  5. Convert the 2D array to a list of tuples.
  6. Return the list of tuples.

Python3




import numpy as np
 
 
def merge(list1, list2):
 
    # Determine the smaller size and slice the arrays accordingly
    size = min(len(list1), len(list2))
 
    arr1 = np.array(list1[:size])
    arr2 = np.array(list2[:size])
 
    # Stack the arrays horizontally and create an array of tuples
    arr = np.column_stack((arr1, arr2))
 
    # Add the remaining sliced elements from the longer list to
    # the end of the resulting array
    if len(list1) > len(list2):
 
        arr = np.concatenate((arr, np.array([(x, '') for x in list1[size:]])))
    elif len(list2) > len(list1):
        arr = np.concatenate((arr, np.array([('', x) for x in list2[size:]])))
 
    # Convert the resulting array to a list of tuples
    merged_list = arr.tolist()
 
    # Return the list of tuples
    return [tuple(i) for i in merged_list]
 
 
# Input lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print(merge(list1, list2))
 
list1 = [1, 2, 3, 4]
list2 = [1, 4, 9]
print(merge(list1, list2))


Output:

[('1', 'a'), ('2', 'b'), ('3', 'c')]
[('1', '1'), ('2', '4'), ('3', '9'), ('4', '')]

Time complexity: O(max(len(list1), len(list2)))

  • The slicing of the arrays in step 2 takes O(min(len(list1), len(list2))) time
  • The stack operation in step 3 takes O(min(len(list1), len(list2))) time
  • The concatenation operation in step 4 takes O(max(len(list1), len(list2)) – min(len(list1), len(list2))) time, which is the difference in length between the two input lists
  • The conversion from 2D array to list of tuples in step 5 takes O(min(len(list1), len(list2))) time
  • Therefore, the overall time complexity is O(max(len(list1), len(list2)))

Auxiliary Space: O(max(len(list1), len(list2)))

  • The numpy arrays created in steps 2 and 3 take O(min(len(list1), len(list2))) space
  • The resulting 2D array after concatenation in step 4 takes O(max(len(list1), len(list2))) space
  • The conversion to list of tuples in step 5 takes O(min(len(list1), len(list2))) space
  • Therefore, the overall space complexity is O(max(len(list1), len(list2)))


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