Python | Combine two lists alternately

NumPy | Python Methods and Functions

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 program for combining 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)) 

Exit:

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

There is an alternative to using list comprehension with zip (), as follows —

Method # 2: Using itertools.cycle()

def countList (lst1, lst2):

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

for item in pair]

# Python3 program to combine two lists
# alternatively

from itertools import cycle

 

def countList (lst1, lst2) :

iters = [ iter (lst1), iter (lst2)]

return l ist ( iter .__ next __ () for iter in cycle (iters))

 
# Driver code

lst1 = [ 1 , 2 , 3 ]

lst2 = [ `a` , ` b ` , ` c` ]

print (countList (lst1, lst2))

Exit:

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

Method # 3: Using reduce()

# Python3 program to combine 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))

Exit:

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

Method # 4: Using the numpy

# Python3 program to combine 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 < / code> ]

lst2 = [ `a` , ` b ` , ` c` ]

print (countList (lst1, lst2))

Exit :

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



Get Solution for free from DataCamp guru