Python – Interleave two lists of different length
Last Updated :
27 Apr, 2023
Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted.
Examples:
Input : test_list1 = ['a', 'b', 'c'], test_list2 = [5, 7, 3, 0, 1, 8, 4]
Output : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a', 4]
Explanation : Alternate elements from 1st list are printed in
cyclic manner once it gets exhausted. Then after exhaustion,
again 1st list starts from 'a', with elements left in 2nd list.
Input : test_list1 = [3, 8, 7], test_list2 = [5, 7, 3, 0, 1, 8]
Output : [3, 5, 8, 7, 7, 3, 3, 0, 8, 1, 7, 8]
Explanation : Alternate elements from 1st list are printed in cyclic manner
once it gets exhausted. 3, 5, 8, 7, 7, 3.. Then after exhaustion,
again 1st list starts from 3, with elements left in 2nd list
Method #1 : Using zip() + cycle() + list comprehension
In this, the repetition of elements in the smaller list is handled using cycle(), and joining is done using zip(). List comprehension performs the task of interleaving simultaneously.
Python3
from itertools import cycle
test_list1 = list ( 'abc' )
test_list2 = [ 5 , 7 , 3 , 0 , 1 , 8 , 4 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = [ele for comb in zip (cycle(test_list1), test_list2) for ele in comb]
print ( "The interleaved list : " + str (res))
|
Output
The original list 1 is : ['a', 'b', 'c']
The original list 2 is : [5, 7, 3, 0, 1, 8, 4]
The interleaved list : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a', 4]
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #2 : Using chain() + zip() + cycle()
Most operations as above method, the only difference being interleaving task is performed using chain().
Python3
from itertools import cycle, chain
test_list1 = list ( 'abc' )
test_list2 = [ 5 , 7 , 3 , 0 , 1 , 8 , 4 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = list (chain( * zip (cycle(test_list1), test_list2)))
print ( "The interleaved list : " + str (res))
|
Output
The original list 1 is : ['a', 'b', 'c']
The original list 2 is : [5, 7, 3, 0, 1, 8, 4]
The interleaved list : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a', 4]
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 3: using the built-in function map().
Python3
from itertools import chain, cycle
test_list1 = list ( 'abc' )
test_list2 = [ 5 , 7 , 3 , 0 , 1 , 8 , 4 ]
res = list (chain( * map ( lambda x, y: [x, y], cycle(test_list1), test_list2)))
print ( "The interleaved list : " + str (res))
|
Output
The interleaved list : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a', 4]
Time Complexity: O(n^2)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...