Lists
Store many items in order — the most-used Python data structure.
What you will learn
- Create and read lists
- Add and remove items
- Loop and slice lists
A list of items
A list holds many values in order, inside square brackets [ ] and separated by commas. Each item has a position number called an index, and counting starts at 0 — so the first item is at index 0, not 1.
colors = ["red", "green", "blue"]
print(colors[0]) # red (first item — index starts at 0)
print(len(colors)) # 3
colors.append("yellow") # add to the end
print(colors)Line by line: we make a list of three colours. colors[0] reaches in at index 0 and gives the first item, red. len(colors) counts how many items there are — 3. colors.append("yellow") adds a new item onto the end of the list. The final print(colors) shows the whole list, now with four colours including the one we just added.
Note: Output: red 3 ['red', 'green', 'blue', 'yellow']
Here are the everyday list actions you will reach for most often:
| Action | Code |
|---|---|
| Add to end | list.append(x) |
| Remove an item | list.remove(x) |
| Length | len(list) |
| Slice (first 2) | list[0:2] |
| Last item | list[-1] |
Watch out: Indexes start at 0, so the first item is list[0] and the last is list[-1].
Q. How do you add an item to the end of a list?
✍️ Practice
- Make a list of 5 subjects and print the first and last.
- Add and remove an item, then print the list.
🏠 Homework
- Build a to-do list: start empty, append three tasks, print them with a loop.