Game Development Reference
In-Depth Information
Because
animals[0]
evaluates to the string
'aardvark'
and
animals[2]
evaluates to the string
'antelope'
, then the expression
animals[0] + animals
[2]
is the same as
'aardvark' + 'antelope'
. This string concatenation evaluates
to
'aardvarkantelope'
.
What happens if we enter an index that is larger than the list's largest index? Try typing
animals[4]
or
animals[99]
into the shell:
>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[4]
Traceback (most recent call last):
File "", line 1, in
animals[4]
IndexError: list index out of range
>>> animals[99]
Traceback (most recent call last):
File "", line 1, in
animals[99]
IndexError: list index out of range
>>>
If you try accessing an index that is too large, you will get an
index error
.
Changing the Values of List Items with Index
Assignment
You can also use the square brackets to change the value of an item in a list. Try typing
animals[1] = 'ANTEATER'
, then type
animals
to view the list.
>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[1] = 'ANTEATER'
>>> animals
['aardvark', 'ANTEATER', 'antelope', 'albert']
>>>
The second item in the
animals
list has been overwritten with a new string.
List Concatenation
You can join lists together into one list with the
+
operator, just like you can join strings.