I can change an element of a list through the following code:
def myFunction(x):
x[0] = 2
myList = [4,5,6]
myFunction(myList)
print(myList) # ==> outputs [2,5,6] (myList[0] is changed to '2' through the function).
But I don't understand why I cannot change a variable using the same code:
def myFunction(x):
x = 2
myNumber = 6
myFunction(myNumber)
print(myNumber) # ==> outputs 6 (myNumber is not changed to '2' through the function).
def myFunction(x):
x = 2
return x
myNumber = 6
myNumber = myFunction(myNumber)
print(myNumber)
You can't change the variable the way you wrote. Instead you can return a value and assign it to a variable.
This method of changing variables globally is not the best way to solve the problem. However; you can do this:
def myFunction(x):
globals()[x] = 2
myNumber = 6
# Must pass variable name as literal string
myFunction("myNumber")
print(myNumber)
Getting a variable as a string is discussed here
I suggest you do something like this (to avoid using globals):
def myFunction():
return 2
myNumber = 6
myNumber = myFunction()
print(myNumber)
More specifically, you would do this for lists:
This is the unconventional global method (not preferred)
def myFunction(x):
globals()[x][1] = 2
myNumbers = [0, 0, 0]
# Must pass variable name as literal string
myFunction("myNumbers")
print(myNumbers)
And the preferred method:
def myFunction():
return 2
myNumbers = [0, 0, 0]
myNumbers[1] = myFunction()
print(myNumbers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With