Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.3 (1 of 3): Lists and arrays

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

One name, many things

You make a shopping list. It has milk, eggs and bread. You do not make three separate notes.

A program needs the same trick. It needs one name for many values: the scores of 30 students, or the songs in a playlist. A list does this job.

Key words

WordWhat it meansExample
Data typeThe kind of thing a value is.integer, string
ListOne name that holds many values in order.["milk", "eggs", "bread"]
ArrayA list of values that are all the same data type.[10, 20, 30]
ElementOne value inside a list."eggs"
IndexThe position number of an element. It starts at 0.index 0 is the first
AppendAdd an element to the end.items.append("tea")
Data structureA way to organise many values.list, dictionary
DictionaryA data structure of keys and values.{"Sam": 16}

The cells students fill in are left blank in this preview.

Watch: one name, many values

Press Play on the short film below. Watch the number that goes with each element: it is the index, and it starts at 0.

Film: lists, one name and many values

Lists: one name, many values

Every scene, as text

  1. A list is one name that holds many values in order. shopping = ["milk", "eggs", "bread"] holds three elements under the one name shopping.
  2. Each element has an index, its position number, and the index starts at 0: "milk" is at index 0, "eggs" at index 1 and "bread" at index 2.
  3. Put an index in square brackets to read one element. print(len(shopping)) shows 3, print(shopping[0]) shows milk and print(shopping[2]) shows bread.
  4. Myth (false): the first element is at index 1. The index counts steps from the start, so the first element is at index 0, and print(shopping[1]) shows eggs, the second element.
  5. A list with 3 elements has indexes 0, 1 and 2. print(shopping[3]) stops with IndexError: list index out of range, because there is no fourth element.
  6. items = ["milk", "eggs"], then items.append("bread") adds "bread" to the end, at index 2. An array holds values that are all the same type: in Python, a list of one type. Either way, the index starts at 0.

Try it: make a list

Code: python
shopping = ["milk", "eggs", "bread"]
print(shopping)
print(len(shopping))
print(shopping[0])
print(shopping[2])

# len() counts the elements.
# Change shopping[2] to shopping[1] and run again.

Make a free account to save your work and track your progress.

Worked example: the index starts at 0

Index012
Element"milk""eggs""bread"
Count (what a person says)firstsecondthird

The cells students fill in are left blank in this preview.

Counting starts at 0

Warning

Many people think the first element is at index 1. It is at index 0, because the index counts steps from the start. A list with 3 elements has indexes 0, 1 and 2. Asking for index 3 gives an IndexError, because there is no fourth element.

Which index?

Have a go

Which index?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

List or array?

A list can hold mixed types, such as a name, an age and a score. An array holds values that are all the same type, such as ten scores. In many languages an array also has a fixed size.

Python has no built-in array. You use a list as an array when all the values have the same type. Both use an index.

The list commands you need

CodeWhat it doesResult (each row starts with items = ["a", "b", "c"])
items.append("d")Add to the end["a", "b", "c", "d"]
items.insert(1, "x")Put "x" at index 1, push others along["a", "x", "b", "c"]
items.remove("b")Take out the first "b"["a", "c"]
items.pop()Take out the last element and give it backgives "c"; list is ["a", "b"]
items.index("c")Find the index of "c"2
items.count("a")Count how many times "a" is there1
"b" in itemsIs it in the list?True
"z" not in itemsIs it missing?True
items.sort()Put the elements in order["a", "b", "c"]

The cells students fill in are left blank in this preview.

Try it: the list commands

Code: python
items = ["milk", "eggs"]
items.append("bread")
items.insert(0, "tea")
print(items)

items.remove("eggs")
print(items)

last = items.pop()
print(last)
print(items)
print("milk" in items)

# Predict each line before you run it.

Make a free account to save your work and track your progress.

Match the command to its job

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Try it: visit every element

Code: python
scores = [5, 8, 3]
total = 0

for score in scores:
    total = total + score

print(total)

# for visits each element once.
# You will learn for loops fully in the loops lesson.
# Here, just copy the pattern.

Make a free account to save your work and track your progress.

Predict the list

Have a go

Predict the list

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your turn: four list functions

Write four small functions that work on a list.

  1. second_item gives back the item at index 1.
  2. add_and_count adds an item to the end and gives back how many items there are now.
  3. remove_item takes an item out if it is there, and gives back the list.
  4. has_item gives back True if the item is in the list, and False if not.

Press Run Tests to check.

Code: python
def second_item(items):
    # Give back the item at index 1.
    return None


def add_and_count(items, item):
    # Add item to the end of the list. Give back how many items there are now.
    return None


def remove_item(items, item):
    # Take the item out of the list if it is there. Give back the list.
    return None


def has_item(items, item):
    # Give back True if the item is in the list, and False if it is not.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Remember

Important

A list holds many values under one name. The index starts at 0. Use append, insert, remove, pop, count, index, sort, len, in and not in.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.