Merge two sorted lists in Python
Bug


Your code does not work when either the left or right array is empty.



left_item = items1[left_pointer]
right_item = items2[right_pointer]



When item1 or item2 is an empty array this will break with an IndexError. 


if right_pointer &gt;= len(items2):
    sorted_list.extend(items1[left_pointer:])
    break
if left_pointer &gt;= len(items1):
    sorted_list.extend(items2[right_pointer:])
    break



You should move this piece of code up to avoid the issue. Now it will break when either is empty.

Tests


I think you can improve your tests quite some bit using the builtin unittest framework.




import unittest

class TestMergeSort(unittest.TestCase):
    def test_normal_merge(self):
        left = [1, 4, 7]
        right = [2, 3, 6, 9]
        out = [1, 2, 3, 4, 6, 7, 9]
        self.assertEqual(merge(left, right), out)

    def test_right_empty(self):
        left = [1, 4, 7]
        right = []
        out = [1, 4, 7]
        self.assertEqual(merge(left, right), out)

    def test_left_empty(self):
        left = []
        right = [2, 3, 6, 9]
        out = [2, 3, 6, 9]
        self.assertEqual(merge(left, right), out)

if __name__ == "__main__":
    unittest.main()


Merge function


An easier way would be to pop the left sides (index=0) of the list and append to the result until either one is empty, after that you can add the remaining to the result.
Naming: I believe you should rename your item1 and item2 to left and right for clarity.
This will no longer have the bug, that it will raise an IndexError when either of the list's are empty.




def merge_sorted_lists(left, right):
    result = []
    while left and right:
        if left[0] &lt; right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    return result + left + right