- Home
- Lessons
- KS3 Computing
- Python: lists
Python: lists
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
A list stores many values under one name. Instead of 30 variables for 30 test scores, you need just one list.
Making and indexing a list
pets = ["cat", "dog", "fish"]
print(pets[0])
print(pets[2])
print(len(pets))
Output:
cat
fish
3
Each item has an index (position). Python counts from 0, so pets[0] is the first item.
len() gives the number of items.
print(pets[0])
print(pets[2])
print(len(pets))
Output:
cat
fish
3
Each item has an index (position). Python counts from 0, so pets[0] is the first item.
len() gives the number of items.
Changing a list
pets = ["cat", "dog", "fish"]
pets.append("rabbit")
print(len(pets))
print(pets[3])
Output:
4
rabbit
append adds an item to the end. You can replace an item by its index:
scores = [4, 7, 2, 9]
scores[1] = 10
print(scores)
prints [4, 10, 2, 9].
pets.append("rabbit")
print(len(pets))
print(pets[3])
Output:
4
rabbit
append adds an item to the end. You can replace an item by its index:
scores = [4, 7, 2, 9]
scores[1] = 10
print(scores)
prints [4, 10, 2, 9].
Looping through a list
scores = [4, 7, 2, 9]
total = 0
for s in scores:
total = total + s
print(total)
The loop visits each item in turn, adding it to total: 4 + 7 + 2 + 9 = 22.
Lists are a kind of data structure. Other data structures include tables (rows and columns) and arrays.
total = 0
for s in scores:
total = total + s
print(total)
The loop visits each item in turn, adding it to total: 4 + 7 + 2 + 9 = 22.
Lists are a kind of data structure. Other data structures include tables (rows and columns) and arrays.
What does this print?
pets = ["cat", "dog", "fish"]
pets.append("rabbit")
print(len(pets))
print(pets[3])
- After append, the list is cat, dog, fish, rabbit: 4 items.
- Index 3 is the fourth item: rabbit.
Answer: 4 then rabbit
A list holds many items under one name. Indexes start at 0. len() counts items, append adds to the end, and a for loop can visit every item.
Check you have got it
Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.