Immutable vs. Mutable
Â
Immutable objects in python are built-int datatypes (e.g.
int
, float
, bool
, string
, Unicode
and tuple
. These objects cannot be changed after creation.my_tuple = (1, 2, 3, 4) my_tuple[0] = 8 # Error! Cannot modify tuples! message = "hello there" message[0] = 'p' # Error! Cannot modify string!
Â
Mutable objects include lists, dictionaries, sets and custom classes.
my_list = [1, 2, 3] my_list.append(4) # can add to the end
Â
Immutable objects are passed into functions by value whereas mutable objects are passed in by reference.
Â
Example of mutable
def someFunction(some_list: list): some_list.append(4) original_list = [1, 2, 3] someFunction(original_list) print(original_list) # outputs: [1, 2, 3, 4]
Â
Example of immutable
def someFunction(some_number: int): some_number = some_number + 4 print(some_number) original_num = 2 someFunction(original_num) # Prints 6 print(original_num) # Prints 4