AdInt
Reading Questions
Quiz
Mutability
- Ints, floats, strings, and booleans are immutable
- Lists are mutable, they can be changed
For example, assigning to an index in a string produces an error
text = "spam" text[0] = "S" # this is an error print(text)
But assigning to an index of a list is allowed
integers = [0, 1, 2] integers[0] = -1 print(integers) # this will print [-1, 1, 2]
- This can lead to confusion with list methods
- Some methods mutate the list, others do not
For example, with strings the upper method does not change the text
text = "spam" text.upper() print(text) # this will print "spam"
So the method returns a new string, which must be used to update the variable
text = "spam" text = text.upper() print(text) # this will print "SPAM"
But with lists, a method can modify the lists
list = [1, 2, 3] list.reverse() print(list) # this will print [3, 2, 1]
If the method is used like the string upper method
list = [1, 2, 3] list = list.reverse() print(list) # this will print None
- Unexpected things may happen
- The
reverse
method modifies the list and does returns None - So using assignment with None overwrites the list with None
- Some list methods mutate, some return something
Some list method mutate and return
list = [1, 2, 3] print(list.pop()) # prints 3 print(list) # prints [1, 2]
Concatenate Vs Append
In the last lab we generated a list of random numbers by doing the following
numbers = [] for i in range(SIZE): numbers += [random.randrange(SIZE)]
- This is just like what we did with strings, create a new list by repeatedly adding on to the end
- One thing to note though is that it creates a new list every time
- If SIZE is large, the program is noticably slow
- With strings we had to do this, but strings are immutable
Lists, however, are mutable, we can change them
numbers = [] for i in range(SIZE): numbers.append(random.randrange(SIZE))
- This adds a new element to the end of the list, without creating a new one
This code is functionally equivalent, but it is more effiecient