Lists
In this tutorial, we'll store ordered, changeable collections.
A list stores multiple values in order.
names = ["Ada", "Grace", "Linus"]
Lists are useful when you have several related items: names, scores, products, messages, or tasks.
Accessing Items
Python starts counting at 0.
names = ["Ada", "Grace", "Linus"]
print(names[0])
print(names[1])
Output:
Ada
Grace
The first item is at index 0, not index 1.
Changing Lists
Lists are mutable, which means they can change.
tasks = ["wash dishes", "feed cat"]
tasks.append("do homework")
print(tasks)
You can update an item:
tasks[0] = "wash plates"
You can remove an item:
tasks.remove("feed cat")
Looping Over Lists
Lists work well with for loops:
scores = [8, 10, 7]
for score in scores:
print("Score:", score)
This runs once for each item.
Common Mistake
An index that does not exist causes an error:
names = ["Ada", "Grace"]
print(names[2]) # error
There are only two items, so the valid indexes are 0 and 1.
Checking Before You Access
If you are not sure how long a list is, use len():
names = ["Ada", "Grace"]
print(len(names))
You can use the length to avoid guessing. As a beginner, it is worth printing the list and its length when something feels confusing.
Practice
Create a list of five favourite foods. Print the first item, the last item, then add one more food.