How the Function Interacts with Its Arguments
Understanding how functions interact with their arguments is crucial for writing effective and reliable code. In this section, we will explore the behavior of functions when it comes to manipulating their arguments.
Let's start with a simple example to demonstrate the behavior of changing the value of a parameter inside a function:
def bank(money):
print("I got", money)
money = 9999
print("I have", money)
salary = 1500
bank(salary)
print(salary)
Upon running this code, the output will be:
From this example, we can conclude that changing the value of a parameter inside a function does not affect the original argument. In other words, when a function receives an argument, it receives the value of the argument, not the argument itself. This behavior is true for scalar values like integers or strings.
However, when working with lists, there are some peculiarities to consider. Let's take a look at the following example:
def bank(cash_in):
print("Print #1:", cash_in)
print("Print #2:", donation)
cash_in = [100, 200]
print("Print #3:", cash_in)
print("Print #4:", donation)
donation = [50, 90]
bank(donation)
print("Print #5:", donation)
Running this code will produce the following output:
Here, we observe that changing the value of the cash_in
parameter does not affect the original list, donation. This aligns with our previous understanding. However, if we modify the list itself identified by the parameter, it will reflect the change outside the function.
To illustrate this, consider the following modified example:
def bank(cash_in):
print("Print #1:", cash_in)
print("Print #2:", donation)
del cash_in[0] # Pay attention to this line.
print("Print #3:", cash_in)
print("Print #4:", donation)
donation = [50, 90]
bank(donation)
print("Print #5:", donation)
When running this code, the output will be:
As you can see, modifying the list identified by the parameter cash_in
affects the original list donation. This behavior arises because lists, unlike scalars, are stored and passed by reference.
Understanding these nuances is crucial when working with functions and their arguments, especially when dealing with mutable data types like lists. By grasping how changes propagate or don't propagate, you can write more reliable and predictable code.