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

Patricia Arquette
Release: 2024-10-27 04:24:02
Original
580 people have browsed it

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)
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!