Coding Curriculum - Python

Using lists

Python has a useful way you can store a list of things (things being strings, characters, numbers...). This is an example of a list:

listOfFlavours = ['chocolate', 'cookies and cream', 'vanilla', 'strawberry']

Notice the syntax: a list is declared using these [ ] square brackets. There are many ways to expand the use of lists and there are many things you can do with them. Combined with raw_input() you can add some items in the list:

newFlavour = raw_input("What new flavour do you have?")
# You say: pistachio 
listOfFlavours.append(newFlavour)

The append() function will add a new item to the end of the list, so it now looks like this:

listOfFlavours = ['chocolate', 'cookies and cream', 'vanilla', 'strawberry', 'pistachio']

Also, lists have indexes. This means every item in order has a number, starting from 0. In our listOfFlavours list, 'chocolate' is 0, 'cookies and cream' is 1, and so on. If you wanted to access a certain item in the list and you knew it's position, you can get it like this:

flavour = listOfFlavours[3] 
print flavour

# Can you guess what this will return?
strawberry
# Because remember, the indexing starts at 0

In a picture, here is what your list looks like (try not to drool):

Great, now you can ask the user for information and you know how to store that information inside a list. Also, you can access different items in lists by using the index.

Before we get started, let's look at one final thing: the while loop.