Home >Backend Development >Python Tutorial >How Can I Pythonically Interleave Two Lists of Unequal Lengths?
Pythonic Interleaving of Lists
Combining two lists in an alternating fashion is a common task in programming. When the first list has exactly one more item than the second, there are several approaches to achieve this in Python. Here are a few Pythonic options:
1. Using Slicing:
One method is to use slicing to create a new list that interleaves the elements from both lists. This can be done with the following steps:
Here's an example:
list1 = ['f', 'o', 'o'] list2 = ['hello', 'world'] result = [None]*(len(list1)+len(list2)) result[::2] = list1 result[1::2] = list2 print(result)
Output:
['f', 'hello', 'o', 'world', 'o']
2. Using the itertools Package:
Python's itertools package provides a convenient function called islice that can be used to iterate over elements of a list in a specified interval. Here's how you can use it to interleave two lists:
import itertools list1 = ['f', 'o', 'o'] list2 = ['hello', 'world'] result = list(itertools.chain(*itertools.zip_longest(list1, list2))) print(result)
Output:
['f', 'hello', 'o', 'world', 'o']
The above is the detailed content of How Can I Pythonically Interleave Two Lists of Unequal Lengths?. For more information, please follow other related articles on the PHP Chinese website!