What is the output of this code snippet?
def depreciation1(asset_value, rate): asset_value = asset_value * rate def depreciation2(asset_values, rate): for i in range(len(asset_values)): asset_values[i] = asset_values[i] * rate asset_value = 10 depreciation1(asset_value, 0.9) print(asset_value) my_asset_values = [10, 100, 1000] depreciation2(my_asset_values, 0.9) print(int(my_asset_values[0]))
This puzzle demonstrates that parameters are called by object in Python. What does that mean?
We look into two functions depreciation1 and depreciation2. The functions take an asset value or a list of asset values as inputs. They depreciate this value by multiplying it with the depreciation rate.
Let us start with the function depreciation1. We start with the global variable asset_value that is 10. We would expect that the function multiplies this with 0.9 leading to a result of 9. However, this is not the case. The variable asset_value within the function scope is a different variable than the global variable asset_value. It shadows the global variable. The global variable asset_value still points to the old value 10. The local variable asset_value now points to the new value 9.
The function depreciation2 behaves differently. We hand over a list of values. Within the function, the local variable asset_values still points to the original list. As the list is a mutable data structure, we can depreciate the individual list values. This has an effect on the global variable asset_values that points to the same list.
Related Video
Solution
10
9