hact77
hact77

Reputation: 1

Modifying global variable from within function that have the same parameter name in python

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]

Upvotes: 0

Views: 28

Answers (2)

flevin
flevin

Reputation: 11

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]

Upvotes: 1

jfschaefer
jfschaefer

Reputation: 54

The problem is that you overwrite the variable L, instead of modifying it. You can use

L[:] = [4,5,6]

instead of

L = [4,5,6]

Upvotes: 0

Related Questions