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
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))
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!