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))
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.