5. Lists

What is a list?

A list is like a variable but it is able to store multiple values.

A list can be thought of as a lot of boxes (variables) stuck together. The stuck together boxes are given a single name, with each individual box given an index number, starting from 0.


Lists in Python

To create an empty list.

  myList = []

To create a list with items in it.

  myList = [“A”, “B”, “C”]

To print the whole list.

    print(myList)


List Indexing

Each item in the list (individual box) has an index number.

Index numbers start at 0.

We can use the list name and the number of the item to ‘index’ or ‘access’ it.

The code below will output “B”

myList = [“A”, “B”, “C”]

print(myList[1])


Iterating through a List

We can use a FOR LOOP to loop through each item in the list.

myList = [“A”, “B”, “C”]

for item in myList :  

      print(item)

The code above will output the following:


Appending to a List

We use the append function to add items on to the end of a list.

    myList = [“A”, “B”, “C”]

    myList.append(“D”)

    myList.append(“E”)

    print(myList) # will output the entire list

    print(myList[3]) # will output item at index position 3

The code above will output the following: