How to Interleave Multiple Lists in Python?

Mary-Kate Olsen
Release: 2024-11-20 21:38:15
Original
959 people have browsed it

How to Interleave Multiple Lists in Python?

Interleaving Multiple Lists: A Pythonic Approach

In Python, interleaving lists of the same length is a common task. Consider the example of two lists: [1,2,3] and [10,20,30]. Our goal is to transform them into [1,10,2,20,3,30].

For a concise solution, we can employ a list comprehension with the zip function. The zip function takes two lists and creates a list of pairs, where each pair contains one element from each list. We iterate over these pairs and create a new list by including all elements in the pairs. Here's the code:

l1 = [1, 2, 3]
l2 = [10, 20, 30]
result = [val for pair in zip(l1, l2) for val in pair]
print(result)  # Output: [1, 10, 2, 20, 3, 30]
Copy after login

This approach works efficiently for interleaving pairs of lists. However, if we have multiple lists to interleave, say N lists, we can extend this solution as follows:

lists = [l1, l2, ...]  # Assume lists contains N lists
result = [val for tup in zip(*lists) for val in tup]
print(result)
Copy after login

By using the * operator before lists in the zip function, we can unpack the list of lists into individual arguments, allowing us to interleave all lists simultaneously. This technique proves useful for handling multiple lists of arbitrary lengths.

The above is the detailed content of How to Interleave Multiple Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template