Basic lists in Python

Listen to this page

Often you will want to store multiple items of related information. This could be as simple as a few colour options for your turtle to use in turn, or a complex combination of data.

List creation

Lists are created by specifying a variable, and assigning data to it using the assignment operator. You can create a list with or without existing data:

kings= []
Empty list
rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
Creating a list and assigning data

Adding to a list

To add an item to a list, use the ‘append’ function. Note that you have to specify what you are appending to – in this case, the ‘kings’ list created earlier.

kings.append('Henry II')
kings.append('Edward I)
print(kings)
['Henry II', 'Edward I']
Adding to a list

Looping over a list

You will often want to perform the same action on a list over and over, for example, when printing each item in the list, or producing a sum of each number stored.

for king in kings:
    print(king)
Printing each item in a list

Accessing a specific item

Sometimes you might need to access a specific item in a list. If you know where in the list it was stored, you can use the index of the item to access it. Lists indices start at 0 and each item is added to the next empty ‘slot’. If we add another item to our list of kings, it would look like this:

list of kings
List of kings
print(kings[2])
Edward II
Accessing the 3rd item in the list