Home >Backend Development >Python Tutorial >How Can I Pythonically Interleave Two Lists of Unequal Lengths?

How Can I Pythonically Interleave Two Lists of Unequal Lengths?

Barbara Streisand
Barbara StreisandOriginal
2024-12-12 16:41:16894browse

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:

  1. Create a new list with a length equal to the sum of the lengths of the two input lists.
  2. Assign the even-indexed elements of the new list to the items from the first input list.
  3. Assign the odd-indexed elements of the new list to the items from the second input list.

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!

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