Liam Hayes
Liam Hayes

Reputation: 141

Python. How come my passed variables aren't being updated? Aren't they being passed by reference?

I'm trying to figure out how to pass these values by reference.

I would like to print the "aNumber" variable as having the value 100, but is in not being updated.

And I would like to print the "someList" list as having the value (100, 100), but it is not being updated.

Any idea why?

Thank you very much.

This is the program:

#################################

def makeIt100(aVariable):
    aVariable = 100

aNumber = 7
print(aNumber)

makeIt100(aNumber)

print(aNumber)

##################################

def changeTheList(aList):
    aList = (100, 100)

someList = (7, 7)
print(someList)

changeTheList(someList)

print(someList)

##################################

This is the result I get:

7
7
(7, 7)
(7, 7)

Upvotes: 0

Views: 28

Answers (1)

iammax
iammax

Reputation: 473

Try something like this, with a return statement in your function:

def makeit100():
    return 100


aVariable = 7
print aVariable #(should print 7)
aVariable = makeit100()
print aVariable #(should print 100)

Essentially, the variable used inside your defined function is not really the same as the one outside, even if it has the same name; it is created when the function is called, then disposed of after.

Upvotes: 2

Related Questions