Home > Backend Development > Python Tutorial > How Can I Efficiently Interleave Unequal-Length Lists in Python?

How Can I Efficiently Interleave Unequal-Length Lists in Python?

Linda Hamilton
Release: 2024-12-08 11:59:11
Original
302 people have browsed it

How Can I Efficiently Interleave Unequal-Length Lists in Python?

Pythonic Interleaving of Unequal-Length Lists

The Pythonic solution to interweaving two lists of different lengths is more efficient and elegant than the provided loop approach. By taking advantage of slicing, the task can be accomplished in a single line of code.

Consider the following example, where the first list contains one more item than the second:

list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
Copy after login

The desired output is:

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

Using slicing, this can be achieved as follows:

result = [None]*(len(list1)+len(list2))
result[::2] = list1
result[1::2] = list2
Copy after login

This approach creates a new list, result, that has enough space to accommodate the elements from both input lists. The slicing operators [::2] and [1::2] assign every other element to the corresponding input list.

The result is a new list that alternates elements from both input lists, as desired. This method is more concise, efficient, and Pythonic than the loop approach.

The above is the detailed content of How Can I Efficiently Interleave Unequal-Length Lists 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