Game Development Reference
In-Depth Information
9 - Hangman
['apples', 'oranges', 'HELLO WORLD']
>>>
Lists are a good way to store several different values into one variable. The individual
values inside of a list are also called items . Try typing: animals = ['aardvark',
'anteater', 'antelope', 'albert'] to store various strings into the variable
animals . The square brackets can also be used to get an item from a list. Try typing
animals[0] , or animals[1] , or animals[2] , or animals[3] into the shell to see
what they evaluate to.
>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[0]
'aardvark'
>>> animals[1]
'anteater'
>>> animals[2]
'antelope'
>>> animals[3]
'albert'
>>>
The number between the square brackets is the index . In Python, the first index is the
number 0 instead of the number 1. So the first item in the list is at index 0, the second item
is at index 1, the third item is at index 2, and so on. Lists are very good when we have to
store lots and lots of values, but we don't want variables for each one. Otherwise we would
have something like this:
>>> animals1 = 'aardvark'
>>> animals2 = 'anteater'
>>> animals3 = 'antelope'
>>> animals4 = 'albert'
>>>
This makes working with all the strings as a group very hard, especially if you have
hundreds or thousands (or even millions) of different strings that you want stored in a list.
Using the square brackets, you can treat items in the list just like any other value. Try
typing animals[0] + animals[2] into the shell:
>>> animals[0] + animals[2]
'aardvarkantelope'
>>>
 
Search WWH ::




Custom Search