Home > Software design >  Why can't I change a variable through a method in Python?
Why can't I change a variable through a method in Python?

Time:03-30

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).

CodePudding user response:

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.

CodePudding user response:

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)
  • Related