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
Release: 2024-12-12 16:41:16
Original
903 people have browsed it

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

Output:

['f', 'hello', 'o', 'world', 'o']
Copy after login
Copy after login

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

Output:

['f', 'hello', 'o', 'world', 'o']
Copy after login
Copy after login

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!

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