Changing the global variable from the function that has the same parameter name in Python

advertisements

I have this function:

def applychange(L):
    result=3+2
    L=[4,5,6]
    return result
L = [1,2,3]
print(applychange(L))
print(L)

and the result is :

5
[1, 2, 3]

how to change the L variable to new value to have this result:

5
[4, 5, 6]


If your goal is to modify L as global variable you need to declare it as such.
For your code to run as intended, insert global L after the result assignment in your function.
Additionally, there is no need to pass L to the function in order to modify L.

def applychange():
    result = 3 + 2
    global L
    L = [4, 5, 6]
    return result

L = [1, 2, 3]
print(applychange())
print(L)

Your code written this way will result in the intended output:

5
[4, 5, 6]