Parameter Passing in Python

In the previous article, we have explored variable length arguments, now we will look at Parameter Passing in Python. When we pass a parameter to a function, how is it passed? Does it contain the same reference to a variable or a different variable, if we make any changes to this variable is it reflected outside? Let us try to understand through some examples:

def fun(x)
     x=15
x=10
fun(x)
print(x)
#Program 1
#Passing an integer

What would be the output of the above program? Let us also see another example:

def fun(l)
    l.append(15)
l=[10,20,30]
fun(l)
print(l)
#Program 2
#Passing a List

The output of the first program would be 10, if we look at the program we can see that the variable initialization within the function does not reflect any changes to the main body of the program which also initializes the same variable.

However, in the second program, the output would be [10,20,30,15] which reflects a change in the initial list modified through the use of the function. Why does the variable in the first program remain even after the execution of the function while in the second the function execution changes the list elements? The answer is that in the first example the variable is defined within the function block hence it is a local variable that does not affect the main body of the program, the variable declared with the same name outside the function is created as a separate object with a unique memory address which is not affected by the function. However, in the second example, it is defined in the main body of code and thus becomes a Global variable. There is no local declaration, and the list in the main program body refers to a single object which is modified during the program’s execution.

Other programs can demonstrate this working even further and help develop our understanding.

def fun(x):
    print(id(x))
    x=15
print(id(x))

x=10
fun(x)
print(id(x))
Output:
140391679191040
140391679191200
140391679191040

The id( ) function returns the unique value for each object in python language, initially in the program both the local x and global x refer to the same value of x. The function id is the same, however, once x is defined with the changed value of 15, the id also changes. Hence, the first and last output values are the same.

Here is another program try to guess the output:

def fun(l)
     l=[40,50]
l=[10,20,30]
fun(l)
print(l)

We have a list with values 10,20,30. Initially, both refer to the same object. However, once the function is executed it is handled as different objects.

Output:
[10,20,30]

The next article will look at returning multiple values in Python.

Leave a Comment