Python Programming for Applied Projects
Data Structures
Storing Collections of Data
So far, you've worked with single pieces of information: one number, one string of text, one boolean value. But most programs need to handle collections of data. Think about a list of users, a set of configuration settings, or a directory of phone numbers. Python provides several built-in ways to store these collections, called data structures. The four most common are lists, tuples, dictionaries, and sets. Each has its own strengths and is suited for different tasks.
Ordered Collections: Lists and Tuples
When the order of your items matters, you'll want to use a list or a tuple. Both maintain the sequence of items exactly as you put them in.
A list is a mutable, or changeable, collection of items. Think of it like a grocery list where you can add, remove, or cross off items as you shop.
You create a list by placing items inside square brackets [], separated by commas. Since lists are ordered, you can access any item by its position, or index. The first item is at index 0, the second at index 1, and so on. You can also change items, add new ones, or remove existing ones.
# Create a list of numbers
my_list = [10, 20, 30, 40]
# Access the first item (index 0)
print(my_list[0]) # Output: 10
# Change the second item
my_list[1] = 25
print(my_list) # Output: [10, 25, 30, 40]
# Add an item to the end
my_list.append(50)
print(my_list) # Output: [10, 25, 30, 40, 50]
# Remove an item by its value
my_list.remove(30)
print(my_list) # Output: [10, 25, 40, 50]
A tuple, on the other hand, is immutable. Once you create a tuple, you can't change it. You can't add, remove, or modify items. This makes them faster and more memory-efficient than lists. You'd use a tuple for data you know should not be altered, like the coordinates of a point or the days of the week.
Tuples are created with parentheses (). You can access items by their index, just like with lists, but you can't reassign them.
# Create a tuple
my_tuple = (10, 20, 30)
# Access the third item (index 2)
print(my_tuple[2]) # Output: 30
# Trying to change an item will cause an error
# my_tuple[0] = 5 # This would raise a TypeError
Unordered Collections: Dictionaries and Sets
Sometimes, the order of items doesn't matter as much as how they're labeled or whether they are unique. For these cases, Python offers dictionaries and sets.
dictionary
noun
A mutable collection of key-value pairs. Each key must be unique and is used to look up its corresponding value.
A dictionary stores information in key-value pairs. Think of a real dictionary: you look up a word (the key) to find its definition (the value). In Python, you create dictionaries with curly braces {}, specifying a key and a value separated by a colon.
# Create a dictionary of a user's profile
user_profile = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Access the value associated with the 'name' key
print(user_profile["name"]) # Output: Alice
# Add a new key-value pair
user_profile["email"] = "alice@example.com"
print(user_profile)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email': 'alice@example.com'}
# Update a value
user_profile["age"] = 31
print(user_profile["age"]) # Output: 31
Finally, we have sets. A set is an unordered collection of unique items. This means two things: the items have no specific order, and you can't have duplicate values. Sets are perfect for membership testing (checking if an item is in the collection) and for performing mathematical set operations like union, intersection, and difference.
You create a set using curly braces {}, just like a dictionary, but without the colons.
# Create a set
# Notice the duplicate 'apple' is automatically removed
my_set = {'apple', 'banana', 'cherry', 'apple'}
print(my_set) # Output: {'cherry', 'banana', 'apple'}
# Check if an item is in the set
print('banana' in my_set) # Output: True
print('grape' in my_set) # Output: False
# Add an item
my_set.add('orange')
print(my_set) # Output: {'cherry', 'banana', 'orange', 'apple'}
# --- Set Operations ---
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union: items in either set
print(set_a.union(set_b)) # Output: {1, 2, 3, 4, 5, 6}
# Intersection: items in both sets
print(set_a.intersection(set_b)) # Output: {3, 4}
Choosing the Right Structure
Knowing which data structure to use is key to writing effective code. Here's a quick summary to help you decide.
| Data Structure | When to Use It | Syntax |
|---|---|---|
| List | A collection that can change and where order matters. | [1, 2, 3] |
| Tuple | A collection that should not change and where order matters. | (1, 2, 3) |
| Dictionary | A collection of labeled data (key-value pairs). | {'a': 1} |
| Set | A collection of unique items where order doesn't matter. | {1, 2, 3} |
Now, let's test your understanding of these fundamental building blocks.
Which of the following data structures are ordered, meaning the sequence of items is preserved?
A tuple is an immutable data structure.