Junior — Middle
How do the methods of passing mutable and immutable data to a function differ?
sobes.tech AI
Answer from AI
In Python, mutable and immutable objects are passed to functions by reference, but their behavior when modified inside the function differs.
-
Immutable objects (e.g., numbers, strings, tuples) cannot be changed inside the function. If you try to modify them, a new object is created, and the original remains unchanged.
-
Mutable objects (e.g., lists, dictionaries, sets) can be modified inside the function, and these changes will be visible outside the function because the reference points to the same object.
Example:
def modify_immutable(x):
x = x + 1 # creates a new object
num = 10
modify_immutable(num)
print(num) # Will print 10, original object is unchanged
def modify_mutable(lst):
lst.append(4) # modifies the object by reference
my_list = [1, 2, 3]
modify_mutable(my_list)
print(my_list) # Will print [1, 2, 3, 4], object has changed
Thus, when passing mutable objects, the function can change their state, but when passing immutable objects, it cannot.