Mutability
Just like strings, it is possible to create new lists with additional elements using the + operator and to create new lists without elements using slices. However, this requires copying the entire list and is very slow for large lists. So, lists in Python are mutable. This means that it is possible to add and remove elements from a list. However, it is very easy to make mistakes in your programs if you do not understand how Python represents lists in memory. So in this activity you will explore how list references affect programs.
For each of the following, create reference diagram and specify what the program would print if run.
-
a_string = "1, 2" b_string = a_string b_string += ", 3" print(a_string) print(b_string)
-
a_list = [1, 2] b_list = a_list b_list.append(3) print(a_list) print(b_list)
-
def a_func(a_string): a_string += ", 3" b_string = "1, 2" a_func(b_string) print(b_string)
-
def a_func(a_list): a_list.append(3) b_list = [1, 2] a_func(b_list) print(b_list)