0

I am currently in a python programming class, and I can't understand or I am misunderstanding the behavior of a list/dictionary passed into a function when I can change the original list no matter the scope depth. How do I maintain the integrity of the original list? To me, this essentially makes a list or dictionary global in scope unless it is copied. The first example aliases the original list. The second references and mutates it from the global scope directly. It seems strange that I don't have to declare it a global to mutate the original list. I understand that I can copy the list with [:] and then pass the copied list into a sub function for the recursion to guard it, but that seem strange also.

#Example1
List1 = []

def makeList(aList, num):
    if not num:
        return 0
    else:
        aList.append(num)
        makeList(aList, num - 1)

makeList(List1, 10)
print(List1)

#Example2    
List1 = []

def makeList(num):
    if not num:
        return 0
    else:
        List1.append(num)
        makeList(num - 1)

makeList(10)
print(List1)

0 Answers0