So far, each variable held one thing. But what if you want to store your whole friend list, all your high scores, or a petβs stats? Thatβs where data structures come in! π Think of them as different kinds of containers β some are like a list of items, some are like labelled drawers. Letβs meet the four big ones.
A list holds many items in order, inside square brackets [ ].
You can add, remove, and change items. Items can be any type β even other lists!
| Method | What it does |
|---|---|
append(x) | Adds x to the end |
remove(x) | Removes the first x |
pop() | Removes & returns the last item |
sort() | Sorts the list |
len(list) | How many items (also works on strings!) |
snacks[0], not snacks[1].
Negative indexes count from the end: snacks[-1] = last item.
A tuple looks like a list but uses parentheses ( ),
and it canβt be changed after itβs created. Itβs perfect for things that should stay fixed,
like coordinates or a birthdate.
A dictionary stores key β value pairs inside curly braces { }.
Instead of using an index number, you look things up by a key (like a name or label).
Super useful for real-world data!
| Method | What it does |
|---|---|
pet["name"] | Get a value by key |
pet.get("age") | Safe lookup (wonβt crash if key is missing) |
pet.keys() | All the keys |
pet.values() | All the values |
pet.items() | Both, as pairs |
A set is an unordered collection with no duplicates.
Itβs great for removing repeats or checking if something exists fast. Use curly braces { }
(but no key: value pairs).
[0].
A list comprehension builds a new list in one line using a mini for loop.
Itβs a favourite Python trick β short, readable, and powerful.
Each structure has a personality. Hereβs a quick cheat sheet:
| Structure | Best for | Can change? | Ordered? |
|---|---|---|---|
| π List | A collection of items (friends, scores) | β Yes | β Yes |
| π Tuple | Fixed data (coordinates, dates) | β No | β Yes |
| ποΈ Dict | Look things up by name/key | β Yes | β Yes (Python 3.7+) |
| π― Set | Unique items, fast membership checks | β Yes (add/remove) | β No |
Create a file called playlist.py. Build a program that uses all four data structures:
π§ Bonus: use a for loop to print each song with its index number, and use .items()
to print the dictionary neatly.
[ ], tuples use ( ), dicts & sets use { }.
Try creating each one and printing type() to compare!