Home >Backend Development >Python Tutorial >How can I Interleave Lists in Python using Zip and List Comprehension?

How can I Interleave Lists in Python using Zip and List Comprehension?

DDD
DDDOriginal
2024-11-15 21:06:03209browse

How can I Interleave Lists in Python using Zip and List Comprehension?

Utilizing Zip and List Comprehension for Interleaving Lists

Interleaving lists of equal length in Python is a common task. Given two lists [1,2,3] and [10,20,30], the goal is to transform them into [1,10,2,20,3,30].

Solution Using Zip and List Comprehension:

A concise approach to interleaving lists is to utilize the zip function and list comprehension. The following code accomplishes the task:

[val for pair in zip(l1, l2) for val in pair]

In this code:

  • zip(l1, l2) iterates over pairs of elements from the two input lists.
  • The outer list comprehension ([val for pair in zip(l1, l2)]) creates a new list for each pair.
  • The inner list comprehension ([val for val in pair]) creates a new list for each pair of values.

Extension for Interleaving Multiple Lists:

If there are multiple lists to interleave (N lists), the same concept can be extended using the * operator within zip:

lists = [l1, l2, ...]
[val for tup in zip(*lists) for val in tup]

In this code:

  • zip(*lists) iterates over tuples of corresponding elements from all input lists.
  • The outer list comprehension ([val for tup in zip(*lists)]) creates a new list for each tuple.
  • The inner list comprehension ([val for val in tup]) creates a new list for each tuple of values.

The above is the detailed content of How can I Interleave Lists in Python using Zip and List Comprehension?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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