Junior — Middle
Could you explain what parameter passing in functions means?
sobes.tech AI
Answer from AI
Passing parameters to a function is a way to provide input data to the function for processing. In Python, parameters are passed by object reference, but the behavior depends on the mutability of the object.
- For mutable objects (e.g., lists, dictionaries), changes inside the function affect the original object.
- For immutable objects (e.g., numbers, strings, tuples), a local copy is created inside the function, and the original object remains unchanged.
Example:
def add_element(lst):
lst.append(4) # modify the original list
my_list = [1, 2, 3]
add_element(my_list)
print(my_list) # Outputs: [1, 2, 3, 4]
def increment(n):
n += 1 # local change
num = 5
increment(num)
print(num) # Outputs: 5
Thus, parameters allow a function to work with external data, modify it, or use it for calculations.