Data structures
Store multiple values together
When you're writing Python code, you often need to handle more than one piece of information at a time. This is where data structures come in handy!
Beyond single values
So far, you might have worked with single pieces of data. Think about a number like 10 or a word like "hello". These are simple values. But what if you need to store a list of all your favorite foods? Or perhaps the names and ages of a group of people?
Data structures give you smart ways to organize and manage multiple pieces of data together. They make your code cleaner and more efficient.
The main structures
Python has several built-in data structures. They each have their own strengths. Let's look at the most common ones.
Lists: Ordered collections that can be changed. You can add, remove, or modify items.Tuples: Ordered collections, just like lists, but they cannot be changed after creation.Sets: Unordered collections of unique items. Duplicates are automatically removed.Dictionaries: Collections that store data in key-value pairs. Think of it like a real-world dictionary where each word (key) has a definition (value).Nested data: Structures inside structures, like a list of dictionaries. This is how most real-world and API data is shaped.
# A list of favorite fruits
fruits = ["apple", "banana", "cherry"]
print(fruits)
# A tuple of coordinates
coordinates = (10, 20)
print(coordinates)
# A set of unique numbers
numbers = {1, 2, 2, 3}
print(numbers)
# A dictionary for a person's details
person = {"name": "Alice", "age": 30}
print(person)Which one to use?
Choosing the right data structure is important. It depends on what you want to do with your data.
| Feature | List | Tuple | Set | Dict |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | since 3.7 |
| Mutable | Yes | No | Yes | Yes |
| Duplicates allowed | Yes | Yes | No | keys: no |
| Access by | index | index | membership | key |
| Syntax | [1, 2] | (1, 2) | {1, 2} | {'k': 1} |
- Use a
listwhen you need an ordered collection that can change. - Use a
tuplewhen your collection should not change. It's good for fixed data. - Use a
setwhen you only care about unique items, and order doesn't matter. - Use a
dictionarywhen you need to link values to specific keys for quick lookup.
Don't worry too much about perfection right away. With practice, you'll get a feel for the best choice.
Start learning
Now that you know what data structures are, it's time to dive into each one. You'll learn how to create them, add items, remove items, and much more.
Practice
Try these exercises to lock in what you just learned.