Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Interleave multiple lists of same length

Python | Interleave multiple lists of same length

Given lists of the same length, write a Python program to store alternative elements of given lists in a new list. Let’s discuss certain ways in which this can be performed.

Interleave Multiple Lists of Same Length using Map() and list comprehension

In Python, we can interleave multiple lists of the same length using map() and list comprehension. The map() is used to handle the interleave of lists and the task of insertion at alternate is performed by the list comprehension part of the shorthand code. Only works in Python 2. 

Python




# Python2 code to demonstrate
# to interleave lists
# using map() + list comprehension
 
# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# printing original lists
print ("Original list 1 : " + str(test_list1))
print ("Original list 2 : " + str(test_list2))
 
# using map() + list comprehension
# to interleave lists
res = [i for j in map(None, test_list1, test_list2)
          for i in j if i is not None]
 
# printing result
print ("The interleaved list is : " + str(res))


Output

Original list 1 : [1, 4, 5]
Original list 2 : [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]

Time Complexity: O(n), where n is the length of the input lists. The program uses a single for loop to iterate over the elements of the input lists and map() and list comprehension to interleave the elements.
Auxiliary Space: O(n), as it creates a new list to store the interleaved elements which have the same length as the input lists.

Interleave Multiple Lists of Same Length using List slicing

In Python, we can interleave multiple lists of the same length using list slicing. Power of list slicing of Python can also be used to perform this particular task. We first extend one list to another and then allow the original list to desire alternate indices of the resultant list. 

Python3




# Python3 code to demonstrate
# to interleave lists
# using list slicing
 
# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# printing original lists
print ("Original list 1 : " + str(test_list1))
print ("Original list 2 : " + str(test_list2))
 
# using list slicing
# to interleave lists
res = test_list1 + test_list2
res[::2] = test_list1
res[1::2] = test_list2
 
# printing result
print ("The interleaved list is : " + str(res))


Output

Original list 1 : [1, 4, 5]
Original list 2 : [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]

Time complexity: O(n), where n is the length of the list. The code iterates over the list once to interleave the elements, which takes linear time. The space complexity is O(n), as a new list of the same length as the input lists is created to store the interleaved elements.
Auxiliary space: O(n) where n is the length of the two input lists (test_list1 and test_list2). This space is used to store the interleaved list.

Interleave Multiple Lists of Same length using itertools.chain() + zip()

In Python, we can interleave multiple lists of the same length using itertools. chain() and zip(). The zip() can be used to link both the lists and then the chain() can be used to perform the alternate append of the elements as desired. This is the most efficient method to perform this task. 

Python3




# Python3 code to demonstrate
# to interleave lists
# using zip() + itertools.chain()
import itertools
 
# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# printing original lists
print ("Original list 1 : " + str(test_list1))
print ("Original list 2 : " + str(test_list2))
 
# using zip() + itertools.chain()
# to interleave lists
res = list(itertools.chain(*zip(test_list1, test_list2)))
 
# printing result
print ("The interleaved list is : " + str(res))


Output

Original list 1 : [1, 4, 5]
Original list 2 : [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]

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

Interleave Multiple Lists of Same Length using While loop

In Python, we can interleave multiple lists of the same length using a while loop with two pointers. One additional approach that you can use to interleave multiple lists of the same length is to use a while loop. This approach involves using two pointers, one for each list, and interleaving the elements by alternating between the two pointers. Here is an example of how this could be implemented:

Python3




def interleave_lists(list1, list2):
    # Initialize the result list and pointers for both lists
    result = []
    i = 0
    j = 0
    # Continue the loop as long as either list has unprocessed elements
    while i < len(list1) or j < len(list2):
        # If the first list has unprocessed elements, append the next element
        if i < len(list1):
            result.append(list1[i])
            i += 1
        # If the second list has unprocessed elements, append the next element
        if j < len(list2):
            result.append(list2[j])
            j += 1
    # Return the result list
    return result
 
# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# printing original lists
print ("Original list 1 : " + str(test_list1))
print ("Original list 2 : " + str(test_list2))
 
res = interleave_lists(test_list1, test_list2)
 
# printing result
print ("The interleaved list is : " + str(res))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

Original list 1 : [1, 4, 5]
Original list 2 : [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]

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

Interleave Multiple Lists of Same Length using For Loop

In Python, we can interleave multiple lists of the same length using For loop. Here is the code implementation where we are using for loop to interleave multiple lists.

Python3




# Python2 code to demonstrate
# to interleave lists
 
# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# printing original lists
print ("Original list 1 : " + str(test_list1))
print ("Original list 2 : " + str(test_list2))
 
 
# to interleave lists
res = []
for i in range(0,len(test_list1)):
    res.append(test_list1[i])
    res.append(test_list2[i])
 
# printing result
print ("The interleaved list is : " + str(res))


Output

Original list 1 : [1, 4, 5]
Original list 2 : [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]

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

Interleave Multiple Lists of Same Length using List Comprehension

In Python, we can interleave multiple lists of the same length using list comprehension with a nested loop. Here is the code implementation where we are using List Comprehension to interleave multiple lists.

Python3




# initializing lists
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
# using a list comprehension with a nested loop
# to interleave the two lists
res = [val             # for each value in the pair
       for pair in zip(test_list1, test_list2)  # iterate over pairs of values from the two lists
       for val in pair]  # for each pair, iterate over the values and add them to the result list
 
# printing the result
print("The interleaved list is: ", res)


Output

The interleaved list is:  [1, 3, 4, 8, 5, 9]

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

Interleave Multiple Lists of Same Length using Transpose() function

The transpose() function is used to create a 2D array from the input arrays, where each input array becomes a row in the 2D array. The flatten() method is then used to flatten the 2D array into a 1D array containing interleaved elements from both input arrays. The tolist() method is used to convert the output array to a Python list.

Python3




import numpy as np
 
# initializing arrays
arr1 = np.array([1, 4, 5])
arr2 = np.array([3, 8, 9])
 
# using numpy.interleaved_arrays() function to interleave the two arrays
res = np.interleaved_arrays((arr1, arr2)).ravel()
 
# printing the result
print("The interleaved list is: ", res.tolist())


Output:

The interleaved list is:  [1, 3, 4, 8, 5, 9]

Time complexity: O(n), where n is the length of the input arrays arr1 and arr2.
Auxiliary space: O(n)

Interleave Multiple Lists of Same Length using Functools.reduce()

In Python, we can interleave multiple lists of the same length using Functools. reduce(), operator. add(), and zip(). We use zip(*lst) to first interleave the lists. Then, we use functools. reduce() to concatenate the interleaved elements into a single list. operator.add() is used as the reducing function to concatenate the lists.

Python3




import functools
import operator
 
def interleave_lists(*lst):
    # Interleave the lists using zip() and store in zipped_lists
    zipped_lists = zip(*lst)
    # Concatenate the interleaved elements using functools.reduce()
    interleaved_list = functools.reduce(operator.add, zipped_lists)
    return list(interleaved_list)
 
# Example
test_list1 = [1, 4, 5]
test_list2 = [3, 8, 9]
 
 
# Print original lists
print("Original list 1: ", test_list1)
print("Original list 2: ", test_list2)
 
# Interleave the lists
res = interleave_lists(test_list1, test_list2)
 
# Print the interleaved list
print("The interleaved list is : " + str(res))


Output

Original list 1:  [1, 4, 5]
Original list 2:  [3, 8, 9]
The interleaved list is : [1, 3, 4, 8, 5, 9]


Time complexity: The zip(*lst) operation takes O(n) time to interleave the lists.
The functools.reduce() operation takes O(n) time to concatenate the interleaved elements.
Therefore, the total time complexity of the function is O(n).
Space complexity: The space complexity of the function is O(n), as we create a new list to store the interleaved elements of the input lists.

RELATED ARTICLES

Most Popular

Recent Comments