Open In App

Python - Interleave multiple lists of same length

Last Updated : 24 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When we interleave multiple lists, we mix the items from each list so that they alternate in a new sequence. This is often done when we have lists of the same length and want to combine them, with each item from each list appearing one after another. In this article, we will explore interleaving multiple lists of the same length.

Using itertools.chain()

itertools.chain() efficiently interleaves multiple lists of the same length in one pass, with O(n) time and space complexity for optimal performance.

Example:

Python
import itertools
a = [1, 4, 5]
b = [3, 8, 9]

# Interleave using itertools.chain()
res = list(itertools.chain(*zip(a, b)))
print(res)

Output
[1, 3, 4, 8, 5, 9]

Explanation:

  • This code pairs elements from lists a and b together.
  • Flattens the pairs, creating a single interleaved list res.

Let's explore more methods to interleave multiple lists of same length.

Using List Comprehension

List comprehension is an efficient way to interleave multiple lists of the same length, flattening the grouped elements into a single sequence.

Example:

Python
a = [1, 4, 5]
b = [3, 8, 9]

# Interleave using list comphrehension
res = [i for sublist in zip(a, b) for i in sublist]
print(res)

Output
[1, 3, 4, 8, 5, 9]

Explanation:

  • This pairs elements from lists a and b.
  • Flattens these pairs into an interleaved list.

Using numpy

numpy provides an efficient way to interleave multiple lists of the same length by stacking them into a 2D array and then flattening it. This method is particularly fast for large numerical datasets due to numpy's optimized operations.

Example:

Python
import numpy as np
a = [1, 4, 5]
b = [3, 8, 9]

# Interleave using numpy
res = np.ravel(np.column_stack((a, b)))
print(res)

Output
[1 3 4 8 5 9]

Explanation:

  • This stacks the lists into a 2D array.
  • Flattens it into 1D array, interleaving the elements.

Using itertools.chain.from_iterable()

itertools.chain.from_iterable flattens the result of zip without using extra memory. It's perfect for interleaving multiple lists of the same length, especially with large datasets.

Example:

Python
import itertools
a = [1, 4, 5]
b = [3, 8, 9]

# Interleave using itertools.chain.from_iterable
res = list(itertools.chain.from_iterable(zip(a, b)))
print(res)

Output
[1, 3, 4, 8, 5, 9]

Explanation:

  • This pairs elements from a and b.
  • Flattens the pairs into single list.

Next Article

Similar Reads