New Computer Science Curriculum
Reading Questions
Quiz
Aliasing
- The mutability of lists makes some list operations faster
- It also introduces some potential errors
With strings
a_string = 'spam' b_string = a_string print(a_string, b_string) b_string = a_string + ' is delicious' print(a_string, b_string)
- Changing one string does not affect the other because the concatenate creates a new string
Lists on the other hand
a_list = [1, 2, 3] b_list = a_list print(a_list, b_list) b_string.append(-1) print(a_list, b_list)
- Changing on list affects another list because append does not make a copy, it modifies
- This is called aliasing, and would be simple to avoid if it only occured when you assign on list to another
- Note, if you did need one list to be equivalent to another, without aliasing you can make a copy with a slice
This also happens every time you call a function with a list as a parameter
def a_func(b_list): b_list.append(-1) a_list = [1, 2, 3] a_func(a_list) print(a_list)
- This is desirable sometimes
A function can modify a list instead of returning a list, which can be more efficient than copying the entire list to make a small change