Open In App

Python | Merge two lists alternatively

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length. Examples:

Input : lst1 = [1, 2, 3]
        lst2 = ['a', 'b', 'c']
Output : [1, 'a', 2, 'b', 3, 'c']

Input : lst1 = ['name', 'alice', 'bob']
        lst2 = ['marks', 87, 56]
Output : ['name', 'marks', 'alice', 87, 'bob', 56]

  Method #1 : List comprehension 

Python3




# Python3 program to merge two lists
# alternatively
 
def countList(lst1, lst2):
    return [sub[item] for item in range(len(lst2))
                      for sub in [lst1, lst2]]
     
# Driver code
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(countList(lst1, lst2))


Output:

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

There is an alternative to use list comprehension with zip() as given below – 

Python3




def countList(lst1, lst2):
    return [item for pair in zip(lst1, lst2 + [0])
                                 for item in pair]


  Method #2 : Using itertools.cycle() 

Python3




# Python3 program to merge two lists
# alternatively
from itertools import cycle
 
def countList(lst1, lst2):
    iters = [iter(lst1), iter(lst2)]
    return list(iter.__next__() for iter in cycle(iters))
     
# Driver code
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(countList(lst1, lst2))


Output:

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

  Method #3 : Using reduce() 

Python3




# Python3 program to merge two lists
# alternatively
import operator
from functools import reduce
 
def countList(lst1, lst2):
    return reduce(operator.add, zip(lst1, lst2))
     
# Driver code
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(countList(lst1, lst2))


Output:

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

  Method #4 : Using numpy module 

Python3




# Python3 program to merge two lists
# alternatively
import numpy as np
 
def countList(lst1, lst2):
    return np.array([[i, j] for i, j in zip(lst1, lst2)]).ravel()
     
# Driver code
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(countList(lst1, lst2))


Output:

['1' 'a' '2' 'b' '3' 'c']

Method#5: using recursion

Approach

this approach is a recursive approach. In this approach, a function is defined that takes two lists as arguments. The function first checks if either of the lists is empty. If one of the lists is empty, the function returns the other list. If both lists have elements, the function concatenates the first element of the first list with the first element of the second list, and then calls itself recursively with the second list as the first argument and the remaining elements of the first list as the second argument. The function continues this process until both lists are empty, at which point the concatenated list is returned.

Algorithm

Define a function “merge_alternatively_rec” that takes two lists as arguments.
Check if either of the lists is empty. If so, return the other list.
Otherwise, concatenate the first element of the first list with the result of calling “merge_alternatively_rec” with the second list as the first argument and the rest of the first list as the second argument.
Return the concatenated list.

Python3




def merge_alternatively(lst1, lst2):
    if not lst1:
        return lst2
    if not lst2:
        return lst1
    return [lst1[0], lst2[0]] + merge_alternatively(lst1[1:], lst2[1:])
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(merge_alternatively(lst1, lst2))


Output

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

Time complexity: O(n), where n is the length of the longer input list.
Space complexity: O(n), where n is the length of the longer input list.

METHOD 6: Using a loop and append() method: In this approach, we use a loop and the append() method to merge two lists alternatively. We iterate over the length of the smaller list and add the elements of both lists at the current index. After the smaller list is exhausted, we append the remaining elements of the long list to the merged list.

  1. Initialize an empty list named merged_lst to hold the merged list.
  2. Calculate the minimum length between lst1 and lst2 using the min() function.
  3. Use a for loop to iterate over both lists up to the minimum length.
  4. In each iteration, append the element at the current index from lst1 to merged_lst and then the element at the same index from lst2.
  5. After the loop, use the slicing operator to append any remaining elements from lst1 and lst2 to merged_lst.
  6. Print the merged_lst.

Python3




lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
 
merged_lst = []
min_len = min(len(lst1), len(lst2))
 
for i in range(min_len):
    merged_lst.append(lst1[i])
    merged_lst.append(lst2[i])
 
merged_lst += lst1[min_len:] + lst2[min_len:]
 
print(merged_lst)


Output

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

Time Complexity: O(n), where n is the length of the merged list.

Space Complexity: O(n), where n is the length of the merged list



Previous Article
Next Article

Similar Reads

Merge Two Lists in Python
Let's see how to concatenate two lists using different methods in Python. This operation is useful when we have a number of lists of elements that need to be processed in a similar manner. Input: test_list1 = [1, 4, 5, 6, 5] test_list2 = [3, 5, 7, 2, 5]Output: [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]Explanation: The output list is the list we get from Mergin
6 min read
Python | Merge two lists into list of tuples
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 us
6 min read
Python | Merge corresponding sublists from two different lists
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',
5 min read
Python | Merge two list of lists according to first element
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
6 min read
Python Program For In-Place Merge Two Linked Lists Without Changing Links Of First List
Given two sorted singly linked lists having n and m elements each, merge them using constant space. First, n smallest elements in both the lists should become part of the first list and the rest elements should be part of the second list. Sorted order should be maintained. We are not allowed to change pointers of the first linked list. Example: Inp
4 min read
Python Program To Merge Two Sorted Lists (In-Place)
Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: The output list is in sorted order. Recommended: Pl
5 min read
Python Merge Two Lists Without Duplicates
In Python coding, combining two lists without repeating elements can be a tricky task. It involves skillfully managing data structures to achieve a smooth and effective outcome. In this short guide, we'll explore ways to merge lists in Python, making sure duplicates are handled seamlessly. Python Merge Two Lists Without DuplicatesBelow, are the met
3 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Merge Key Value Lists into Dictionary Python
Sometimes, while working with lists, we can come forward with a problem in which we need to perform the merge function in which we have the key list and need to create dictionary mapping keys with corresponding value in other list. Let's discuss certain ways in which this task can be performed. Merge Key Value Lists into Dictionary Python Using zip
8 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Practice Tags :