Home  >  Article  >  Backend Development  >  How to Zip Lists of Unequal Lengths with Repeating Values in Python?

How to Zip Lists of Unequal Lengths with Repeating Values in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 04:24:02572browse

How to Zip Lists of Unequal Lengths with Repeating Values in Python?

How to Zip Lists of Different Sizes with Repeating Values

When dealing with lists of unequal length, the built-in zip() function can leave you short-changed. The original question seeks a method to zip lists A and B, even if B is shorter, repeating its values as needed.

While the provided code using a loop can achieve this, a more concise solution is available using itertools.cycle. This function returns an iterator that cycles through a provided iterable, repeating it indefinitely.

Solution using itertools.cycle:

from itertools import cycle

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)

In this case, if A is longer than B, the zip_list will pair the values of A with the repeated values of B, ensuring all elements are included. If B is longer than A, the process is reversed.

The itertools.cycle function provides a convenient way to achieve this repeated pairing, making it an efficient solution for handling lists of different sizes in Python.

The above is the detailed content of How to Zip Lists of Unequal Lengths with Repeating Values in Python?. 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