Python Data Structures Essentials
Introduction to Python Data Structures
Organizing Your Data
So far, we've worked with single pieces of data, like one number or one string. But what happens when you need to handle a collection of items? Maybe it's a list of student names, a set of unique usernames, or the coordinates for a point on a map. Python gives us special containers called data structures to organize and manage groups of related data. We'll explore the four most common ones: lists, tuples, dictionaries, and sets.
Lists: The Flexible Organizer
Think of a list like a shopping list. You can write items down in a specific order, add new ones, cross them off, and even have the same item multiple times. In Python, a list is an ordered, changeable collection of items.
Lists are defined by enclosing comma-separated items in square brackets
[].
planets = ["Mercury", "Venus", "Earth", "Mars"]
Because lists are ordered, you can retrieve any item by its position, or index. The catch? Indexing starts at 0, not 1. So, the first item is at index 0, the second is at index 1, and so on.
# Get the first planet
first_planet = planets[0]
print(first_planet) # Output: Mercury
# Get the third planet
third_planet = planets[2]
print(third_planet) # Output: Earth
The most important feature of lists is that they are mutable, a fancy word meaning they can be changed after they are created. You can easily add or remove items.
# Add a new planet to the end of the list
planets.append("Jupiter")
print(planets) # Output: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter']
# Remove a planet by its value
planets.remove("Venus")
print(planets) # Output: ['Mercury', 'Earth', 'Mars', 'Jupiter']
Use a list whenever you need an ordered collection of items that might need to change.
Tuples: Data Set in Stone
Now imagine something that shouldn't change, like the coordinates for a specific location. A tuple (pronounced tupple) is perfect for this. Like a list, a tuple is an ordered collection of items. The key difference is that tuples are immutable—once created, they cannot be modified.
Tuples are created using parentheses
().
# A tuple representing a point in 3D space
point = (10, 20, 5)
# You can access elements by index, just like a list
print(point[0]) # Output: 10
If you try to change an item in a tuple, Python will give you an error. This is a feature, not a bug! It protects your data from being accidentally changed.
# This will cause an error!
point[0] = 15 # TypeError: 'tuple' object does not support item assignment
Use a tuple when you have data that you know should not change, like a collection of constants or fixed coordinates.
Dictionaries and Sets
Lists and tuples store items by their ordered position. Dictionaries and sets are different; they are unordered collections.
dictionary
noun
A mutable, unordered collection of key-value pairs. Think of a real dictionary: you look up a word (the key) to find its definition (the value).
Each key in a dictionary must be unique. You create them using curly braces {} with colons separating keys and values.
student = {
"name": "Alice",
"id": 12345,
"major": "Physics"
}
You don't use a numeric index to get data from a dictionary. Instead, you use the key.
# Access the value associated with the 'name' key
print(student["name"]) # Output: Alice
Dictionaries are mutable. You can add new key-value pairs, change existing values, or remove pairs entirely.
# Add a new key-value pair
student["grad_year"] = 2025
# Change an existing value
student["major"] = "Astrophysics"
print(student)
# Output: {'name': 'Alice', 'id': 12345, 'major': 'Astrophysics', 'grad_year': 2025}
Finally, we have sets. A set is an unordered collection of unique items. The key word here is unique. A set cannot contain duplicate elements.
Sets are also created with curly braces
{}, but they don't have key-value pairs.
# Notice the duplicate 'blue'. It will be removed.
unique_colors = {"red", "green", "blue", "blue"}
print(unique_colors) # Output: {'red', 'green', 'blue'}
Sets are great for membership testing (checking if an item is in a collection) and for removing duplicates from a list.
# Add a new item
unique_colors.add("yellow")
# Remove an item
unique_colors.remove("green")
print(unique_colors) # Output: {'red', 'blue', 'yellow'}
| Data Structure | Ordered | Mutable | Allows Duplicates | Syntax |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [1, 2, 3] |
| Tuple | Yes | No | Yes | (1, 2, 3) |
| Dictionary | No | Yes | Keys are unique | {"a": 1, "b": 2} |
| Set | No | Yes | No | {1, 2, 3} |
Time to check your understanding of these fundamental building blocks.
You're building a to-do list application. Which Python data structure would be the most appropriate choice to store the list of tasks, allowing you to add, remove, and reorder them?
Which of the following data structures is immutable, meaning its contents cannot be changed after it is created?
Choosing the right data structure is a key skill in programming. By understanding the core differences between lists, tuples, dictionaries, and sets, you can write more efficient and readable code.