In Python, interlacing two lists means creating a new list that alternates elements from both lists. To achieve this, consider the following scenarios:
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']
When the input lists have different lengths, additional logic is required:
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
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!