TransWikia.com

Recursive function in python looks like it's acting out of scope, but it is not. What do I miss?

Stack Overflow Asked by Ádám Palkovics on December 13, 2021

I was trying to figure out how the following code works,

def mergeSort(a):
    if len(a) > 1:
        mid = len(a)//2
        left = a[:mid]
        right = a[mid:]
        mergeSort(left)
        mergeSort(right)

        i = j = k = 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                a[k] = left[i]
                i += 1
            else:
                a[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            a[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            a[k] = right[j]
            j += 1
            k += 1
    return a

with Python tutor, when I noticed that the while-loop manipulates the ‘A’ list from the previous call. For me it looks like it’s acting out of scope, but clearly it isn’t.

Can you tell me what I’m missing that I’m thinking it’s replacing elements of a list out of scope?

One Answer

There is no such this as "acting out of scope". The rules of python guarntee that a variable can only be modified when it is in scope.

However, sometimes multiple variables refer to the same object. In the case of a function, this often happens with pass by reference. Here's an example:

def change_element(a):
   a[1] = 42

x = list(range(10)
print(x)
change_element(x)
print(x)

Here you will see the element of x changes because the list is passed to change_element() by reference. This means that x and a both refer to the same list object.

Your example actually does exactly this kind of thing.

Answered by Code-Apprentice on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP