Merge two sorted lists in Python
The merge half of merge sort - two pointers over sorted inputs.
def merge_sorted(left, right):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
return out + left[i:] + right[j:]
How it works
- Walks two sorted lists with indexes
iandj. - Always appends the smaller head to the output.
- Tacks on whatever remains when one list runs out.
Keywords and builtins used here
defelseiflenmerge_sortedreturnwhile
The run, in numbers
- Lines
- 10
- Characters to type
- 210
- Tokens
- 89
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 56 seconds.
Step 9 of 10 in Collections, step 31 of 72 in Language basics.