# Mutability in Python
Last edited: 2025-12-05
In Python Index all variables are references to objects. Every object has a mutability property. Objects that are mutable in Python behave as you would expect: when a variable pointing to a mutable object is altered, the object itself is altered.
x = [1,2]
y = x
x.append(3)
print(y) # [1,2,3]
Here x and y point to the mutable
list object. When x is altered to add 3 to the list, y also reflects this change because both variables point to the same object.
In contrast, when a variable pointing to an immutable object in Python Index is altered, it creates a new object for that variable to point to, whilst the remaining variables continue to point to the original object.
x = 1
y = x
print(x, id(x)) # 1 140703625587616
print(y, id(y)) # 1 140703625587616
x += 1
print(x, id(x)) # 2 140703625587648
print(y, id(y)) # 1 140703625587616
(The id function tells you the location in computer memory
.)
# Passing arguments to functions
In Python Index all arguments are passed by reference to functions. Though the mutability of that variable dictates how the object is treated by that function.
For immutable objects any alteration a function does to the object will not be reflected outside the scope of that function.
def become_worldly(value):
value += ' world'
print("Inside function: ", value)
greeting = 'Hello'
print("Before function: ", greeting) # Before function: Hello
become_worldly(greeting) # Inside function: Hello world
print("After function: ", greeting) # After function: Hello
This behaves as if they have been passed by value ; however, this approach can reduce computer memory usage if multiple variables hold the same value.
For mutable objects, any alterations that the function makes to the passed object will be reflected outside the scope of that function.
def become_worldly(value):
value.append('world')
print("Inside function: ", value)
greeting = ['Hello']
print("Before function: ", greeting) # Before function: ['Hello']
become_worldly(greeting) # Inside function: ['Hello', 'world']
print("After function: ", greeting) # After function: ['Hello', 'world']
! When passing a mutable argument to a function, the function can alter the argument, causing an unintended side effect . It is good practice to avoid side effects in your functions and not to use input parameters as the function’s output .
# Mutable and immutable types in Python
In Python Index , lists, sets and dictionaries are mutable , whereas numbers, strings, tuples and frozen sets are immutable . User-defined objects are mutable by default; however, you can make them immutable if you wish.