Home > Backend Development > Python Tutorial > How to Interleave Two Lists of Unequal Lengths in Python?

How to Interleave Two Lists of Unequal Lengths in Python?

Patricia Arquette
Release: 2024-12-02 05:44:09
Original
862 people have browsed it

How to Interleave Two Lists of Unequal Lengths in Python?

Interlacing Two Lists Alternately in Python

When combining two lists in an alternating manner, where the first list has one more element than the second, Python offers several approaches.

One method involves slicing the lists:

list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
result = [None]*(len(list1)+len(list2))
result[::2] = list1
result[1::2] = list2
Copy after login

This approach creates a new list of length equal to the combined lengths of the input lists. It assigns even-index values from list1 and odd-index values from list2 into the new list, resulting in the desired interleaving effect.

Alternatively, you can use the zip_longest() function from the itertools module:

from itertools import zip_longest
result = list(zip_longest(list1, list2, fillvalue=None))
Copy after login

zip_longest() combines the lists element-wise, filling in the missing values with the specified fillvalue. Since we provide None as the fillvalue, the list with one fewer element will be padded with None values, achieving the desired interlacing. By converting the generator returned by zip_longest() into a list, you obtain the final result.

The above is the detailed content of How to Interleave Two Lists of Unequal Lengths 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