Mutability in Python

In Python Index all variables are references to objects. These objects come with 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 and when x is altered to add 3 to the list, as y points to the same object as x when you look at y it also has been changed.

Whereas when a variable pointing to an immutable object in Python Index is altered, it creates a new object for the altered variable to point to and leaves the rest of the variables pointing to the old 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

These essentially acts as if they have been passed by value, however this technique can reduce computer memory usage if multiple variables hold the same value.

For mutable objects any alteration the function does 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']
 

Beware side effects!

When passing a mutable argument to a function. This function can alter the argument causing an intended side effect of that function. It is good practice to not have side effects of your function and to not use input parameters as the functions 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 by default mutable however you can make them immutable if you so wish.