Home >Backend Development >Python Tutorial >How Can I Efficiently Interlace Two Lists of Potentially Different Lengths in Python?

How Can I Efficiently Interlace Two Lists of Potentially Different Lengths in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 08:43:12548browse

How Can I Efficiently Interlace Two Lists of Potentially Different Lengths in Python?

Pythonic Interlacing: Combining Lists Alternately

In Python, interlacing two lists means creating a new list that alternates elements from both lists. To achieve this, consider the following scenarios:

Length-Matched Lists

If both lists have an equal number of elements, a simple solution is to use slicing:

list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
result = [None] * (len(list1) + len(list2))
result[::2] = list1
result[1::2] = list2
print(result)

This will produce the desired output:

['f', 'hello', 'o', 'world', 'o']

Length-Mismatched Lists

When the input lists have different lengths, additional logic is required:

Leaving Excess Elements at the End

To leave any excess elements from the longer list at the end, use this approach:

def interlace(list1, list2):
    result = []
    i, j = 0, 0  # indices for list1 and list2

    while i < len(list1) and j < len(list2):
        result.append(list1[i])
        result.append(list2[j])
        i += 1
        j += 1

    # Add remaining elements from the longer list
    result.extend(list1[i:] if len(list1) > len(list2) else list2[j:])

    return result

Interspersing Elements Evenly

To spread out excess elements evenly within the interlaced list, use this method:

def interlace_evenly(list1, list2):
    shorter_list = list1 if len(list1) < len(list2) else list2
    longer_list = list1 if len(list1) > len(list2) else list2

    result = []

    # Intersperse elements of the shorter list
    for i in range(len(shorter_list)):
        result.append(shorter_list[i])
        result.append(longer_list[i % len(longer_list)])

    # Add remaining elements from the longer list
    result.extend(longer_list[len(shorter_list):])

    return result

The above is the detailed content of How Can I Efficiently Interlace Two Lists of Potentially Different Lengths in Python?. 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