Reputation: 1
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
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
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