Search code examples
pythonfunctionreturnreturn-valuemergesort

Python: How does merge sort affect the list without an explicit return value?


I have seen a variation of this question in Java but I couldn't understand it. Why is the list change when the function mergeSort is called even though there is no explicit return? I can't get my mind around it. How do the recursive calls return to those calls in the stack? What bit of information am I missing to understand the inner workings of the code to get why mergesort changes alist when mergeSort(alist) is called.

Here's the code from this link:

def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
    mid = len(alist)//2
    lefthalf = alist[:mid]
    righthalf = alist[mid:]

    mergeSort(lefthalf)
    mergeSort(righthalf)

    i=0
    j=0
    k=0
    while i < len(lefthalf) and j < len(righthalf):
        if lefthalf[i] < righthalf[j]:
            alist[k]=lefthalf[i]
            i=i+1
        else:
            alist[k]=righthalf[j]
            j=j+1
        k=k+1

    while i < len(lefthalf):
        alist[k]=lefthalf[i]
        i=i+1
        k=k+1

    while j < len(righthalf):
        alist[k]=righthalf[j]
        j=j+1
        k=k+1
print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

Solution

  • Consider this small example:

    def foo(lst):
        lst[0] = 1000
    
    lst = [10, 20, 30]
    foo(lst)
    print(lst) # prints [1000, 20, 30]
    

    it works because lists, like any other object, are passed by reference.

    If this sounds like something new to you, you should re-read the introductory part of the/any python manual.

    This may be a good reading to understand this concept: https://www.python-course.eu/passing_arguments.php