Hello folks,
Let's test the following functions:
def double(arg):
""" This function takes 'arg' object and multiply it by 2. """
print('Before: ',arg)
arg = arg * 2
print('After: ',arg)
# Calling the function
flist = [10,20]
double(flist )
print('Original : ',flist )
The output will be like this:
Before: [10, 20]
After: [10, 20, 10, 20]
Original: [10, 20]
This means that the arg
object passed to the function by value, and it's changed only within the function suite.
Put in your consideration that Python allow pass by value and pass by reference.
Second function
def change(arg):
""" This function takes 'arg' object and add '30' to it. """
print('Before: ',arg)
arg.append(30)
print('After: ',arg)
# Calling the function
slist = [10,20]
change(slist)
print('Original: ',slist)
The output will be like this:
Before: [10, 20]
After: [10, 20, 30]
Original: [10, 20, 30]
This means that the arg
object passed to the function by reference, and it's changed within the function suite and in the original object (simply it is passed by address).
Let's explain what happens here...
As Python allow the two types of passing objects, why the above functions behave in different ways?
In Python if the passed object is Mutable like lists, dictionaries, and sets are always passed into a function by reference.
and for immutable like strings, integers, tuples are always passed into a function by value.
But it seems that there is an Error with the interpreter.
To understand what happened
Remember that in the first function double
the arg object changed using assignment statement , so what happened that the right side of the assignment statement is executed and a new object created with value of arg * 2, then assigned to arg
with only the function suite, However the original object still exits in the calling code.
On the other hand, because using .append()
both lists in the function suite and the calling code affected by the append() function because both refer to the same object.
This explains what happened.
I hope this small article has been helpful.
Thanks
Top comments (2)
Interesting!
Thank you!
You're welcome, Thanks too! 💚