easy +10 pts

Interleave Two Lists

Merge two lists alternately by index, preserving their original order.

Write a function `interleave(a, b)` that takes two lists `a` and `b` and returns a new list that contains elements from `a` and `b` alternately, starting with `a[0]`, then `b[0]`, then `a[1]`, then `b[1]`, and so on. The lists may be of different lengths. If one list runs out, append the remaining elements of the longer list at the end. The original lists must not be modified. For example, `interleave([1, 2], ['x', 'y', 'z'])` returns `[1, 'x', 2, 'y', 'z']`.

Constraints

Inputs `a` and `b` are lists of length between 0 and 1000, containing any hashable values (e.g., integers, strings). The function should run in O(len(a) + len(b)) time and O(len(a) + len(b)) space.

Example

>>> interleave([1, 2, 3], ['a', 'b'])
[1, 'a', 2, 'b', 3]
>>> interleave([], [1, 2])
[1, 2]
>>> interleave(['x'], [])
['x']
>>> interleave([1, 3], [2, 4])
[1, 2, 3, 4]
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Create an empty result list and use a loop over the maximum length of the two lists.
Append from `a` and `b` only if the index is within that list's length.
Alternatively, use `zip` to pair elements and then add the leftover slice of the longer list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.