2

As I know integers are immutable, how would I go about printing 4 instead of 2?

a = 2
def add(num):
   num = 4
print(a)    
5
  • Can you explain what's going on in this code example? What's your endgame here? Commented Jun 30, 2017 at 0:40
  • 2
    Just because the integer itself is immutable, that doesn't stop you assigning a different integer reference to a. Is that what you are asking? It's not very clear, your question is lacking detail. Commented Jun 30, 2017 at 0:40
  • 1
    add a line return num to your add method Commented Jun 30, 2017 at 0:44
  • 1
    Function parameters are passed by value, not by reference. You can't change the caller's variable from a function. Commented Jun 30, 2017 at 0:56
  • 2
    Possible duplicate of How do I pass a variable by reference? Commented Jun 30, 2017 at 1:34

2 Answers 2

2

In Python, variables are just baskets that hold values. If you want a to hold a different value, just put it in. Simple as that.

a = 2 # value
a = 3 # new value

Although the integer 2 is immutable, a is just an object reference to that integer. a itself - the object reference- can be changed to reference any object at any time.

As you have discovered, you can't simply pass a variable to a function and change its value:

def f(a):
    a = 4
f(a)
print(a) # still 3

Why still 3? Because in Python objects are passed by * object reference*. This is neither the same as by value, nor is it the same as by reference, in other languages.

The a inside of the function is a different object reference than outside of the function. It's a different namespace. If you want to change the function so that its a is the other, final a, you have to explicitly specify that this is what you want.

def f():
    global a # this makes any following references to a refer to the global namespace
    a = 4
f()
print (a) # 4

I highly recommend this link for further reading.

Sign up to request clarification or add additional context in comments.

1 Comment

Or process a mutable type: def f(a): ` a[0]=5` L=[3] f(L) print(L[0]) - a bit convoluted, but it serves as a decent example.
0

Seems like this is what you're trying to achieve:

a = 2
def add():
    global a
    a = 4

add()
print(a)

The add() function will change a's value to 4 and the output would be 4.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.