110 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
We won’t be using the list() function on strings or range objects in this program, but it will
come up in later in this book.
Reassigning the Items in Lists..................................................................................................................................
The items inside a list can also be modified. Use the index with a normal assignment statement.
Try typing the following into the interactive shell:
animals = ['aardvark', 'anteater', 'antelope', 'albert']
animals
['aardvark', 'anteater', 'antelope', 'albert']
animals[2] = 9999
animals
['aardvark', 'anteater', 9999, 'albert']
Reassigning Characters in Strings
While you can reassign items in a list, you cannot reassign a character in a string value. Try
typing the following code into the interactive shell to cause this error:
'Hello world!'[6] = 'x'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
To change a character in a string, use slicing instead. Try typing the following into the interactive
shell:
spam = 'Hello world!'
spam = spam[:6] + 'x' + spam[7:]
spam
'Hello xorld!'
Lists of Lists
List values can even contain other list values. Try typing the following into the interactive shell:
spam = [['dog', 'cat'], [1, 2, 3]]
spam[0]
['dog', 'cat']
spam[0][0]