0

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)
Liam Hayes
  • 141
  • 2
  • 2
  • 9
  • This will clear up your misconceptions: https://nedbatchelder.com/text/names1.html – chepner Jun 23 '17 at 03:33
  • 1
    Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – daemon24 Jun 23 '17 at 03:45
  • Duplicate of https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference – Aanchal1103 Jun 23 '17 at 04:55

1 Answers1

2

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.

iammax
  • 453
  • 2
  • 5
  • 18
  • Okay, so there is no way to do the thing I want to do? Like the way you do it in C++? So I am forced to return? – Liam Hayes Jun 23 '17 at 03:35
  • I don't believe you can do it like that; a return statement is probably your only option. Here's a similar question: https://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller – iammax Jun 23 '17 at 03:38