Python | Merge two lists alternatively

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



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


 
Method #2 : Using itertools.cycle()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

 
Method #3 : Using reduce()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

 
Method #4 : Using numpy module

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.