Home > Article > Backend Development > 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]
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)
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!