You might have noticed that the
ALLSHAPES variables are tuples instead of lists. When do we want to use tuples and when do we want to use lists? And what’s the difference between them anyway?
Tuples and lists are the same in every way except two: tuples use parentheses instead of square brackets, and the items in tuples cannot be modified (but the items in lists can be modified). We often call lists mutable (meaning they can be changed) and tuples immutable (meaning they cannot be changed).
For an example of trying to change values in lists and tuples, look at the following code:
>>> listVal = [1, 1, 2, 3, 5, 8] >>> tupleVal = (1, 1, 2, 3, 5, 8) >>> listVal = 'hello!' >>> listVal [1, 1, 2, 3, 'hello!', 8] >>> tupleVal = 'hello!' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> tupleVal (1, 1, 2, 3, 5, 8) >>> tupleVal 5
Notice that when we try to change the item at index
2 in the tuple, Python gives us an error message saying that tuple objects do not support "item assignment".
There is a silly benefit and an important benefit to tuple’s immutability. The silly benefit is that code that uses tuples is slightly faster than code that uses lists. (Python is able to make some optimizations knowing that the values in a tuple will never change.) But having your code run a few nanoseconds faster is not important.
The important benefit to using tuples is similar to the benefit of using constant variables: it’s a sign that the value in the tuple will never change, so anyone reading the code later will be able to say, "I can expect that this tuple will always be the same. Otherwise the programmer would have used a list." This also lets a future programmer reading your code say, "If I see a list value, I know that it could be modified at some point in this program. Otherwise, the programmer who wrote this code would have used a tuple."
You can still assign a new tuple value to a variable:
>>> tupleVal = (1, 2, 3) >>> tupleVal = (1, 2, 3, 4)
The reason this code works is because the code isn’t changing the
(1, 2, 3) tuple on the second line. It is assigning an entirely new tuple
(1, 2, 3, 4) to the
tupleVal, and overwriting the old tuple value. You cannot however, use the square brackets to modify an item in the tuple.
Strings are also an immutable data type. You can use the square brackets to read a single character in a string, but you cannot change a single character in a string:
>>> strVal = 'Hello' >>> strVal 'e' >>> strVal = 'X' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment