0

I write the following program to see how function works in Python

def mylove(a):
    a=a+1
a=2
mylove(a)
print(a)

When I print(a), why it is 2 not 3


On the other hand for the following code

def puzzle(name):   
    name.pop()

name=['s','s','s']
puzzle(name)
print(name)

We have the result ['s','s']

89085731
  • 141
  • 5
  • 1
    Because inside of the function, `a` refers to the function parameter, not the global variable `a`. So, you increase the value of the parameter, then exit the function, losing that value and the global `a` is still `2`. A good editor or IDE (like VSCode or PyCharm) would warn you, it's called shadowing when you reuse a name from the outer scope. – Grismar Jan 05 '21 at 23:14
  • you didn't return `a` from your function. if you had, you would still need to re-assign it – Paul H Jan 05 '21 at 23:17

1 Answers1

1

Integers are immutable data types, so they cannot be changed.

The line

a +=1

is a shortcut for

a=a+1

What is happening is that inside the scope of the function, the variable label 'a' is being assigned to a new different integer, while the original integer as an object in memory remains unchanged.

Outside of the function, the label 'a' still points to the original unchanged integer object.

The id() function can be used to show you if the underlying memory object of two variables is the same

>>> a =1
>>> def f(a):
...  print('before',id(a))
...  a+=1
...  print('after',id(a))
...
>>> print('outside',id(a));f(a);print('outside',id(a))
outside 504120010720
before 504120010720
after 504120010752
outside 504120010720
>>>

The after object is a different object than the other three.

In contrast, something mutable like a list can be used to send changes out of a function.

>>> b=[]
>>> def g(b):
...  print('before',id(b))
...  b.append(5)
...  print('after',id(b))
...
>>> print('outside',id(b));g(b);print('outside',id(b))
outside 504083879680
before 504083879680
after 504083879680
outside 504083879680
>>> print(b)
[5]

The after object is the same object as the other three.

The bottom line is that append() modifies the same object in memory, modifications are only allowed for mutable objects.

Doin a += does not modify the original object but produces an entirely new object which is assigned to the variable name.

Matt Miguel
  • 1,325
  • 3
  • 6