Categories
Python Answers

How to interleave multiple lists of the same length in Python?

Spread the love

Sometimes, we want to interleave multiple lists of the same length in Python.

In this article, we’ll look at how to interleave multiple lists of the same length in Python.

How to interleave multiple lists of the same length in Python?

To interleave multiple lists of the same length in Python, we can use list comprehension and zip.

For instance, we write:

l1 = [1, 2]
l2 = [3, 4]
l3 = [5, 6]
lists = [l1, l2, l3]
l = [val for tup in zip(*lists) for val in tup]
print(l)

We have 3 lists l1, l2, and l3.

And then we put them into the lists list.

Then to interleave all the lists, we call zip with all the lists in lists as arguments.

Then we use [val for tup in zip(*lists) for val in tup] to interleave the elements by taking the items from the tuples.

Therefore, l is [1, 3, 5, 2, 4, 6].

Conclusion

To interleave multiple lists of the same length in Python, we can use list comprehension and zip.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *