Now that you understand the different types of collections available in Python. lists, tuples, dictionaries, and sets. let's put that knowledge into practice. This section provides hands-on examples to help solidify your understanding of how to create, manipulate, and use these fundamental data structures. Follow along and try running these examples in your Python interpreter or script.
Lists are ordered, mutable collections. They are perhaps the most common collection type you'll encounter. Let's manage a list of tasks.
Create a list: Start by creating a list of strings representing tasks.
tasks = ["Review Chapter 3", "Start Chapter 4", "Practice list operations"]
print(tasks)
# Output: ['Review Chapter 3', 'Start Chapter 4', 'Practice list operations']
Access elements: Access elements using their index (remembering that indexing starts at 0).
first_task = tasks[0]
print(f"First task: {first_task}")
# Output: First task: Review Chapter 3
last_task = tasks[-1] # Negative indexing counts from the end
print(f"Last task: {last_task}")
# Output: Last task: Practice list operations
Add elements:
Use append()
to add an item to the end, or insert()
to add at a specific position.
tasks.append("Take a break")
print(tasks)
# Output: ['Review Chapter 3', 'Start Chapter 4', 'Practice list operations', 'Take a break']
tasks.insert(1, "Read list documentation") # Insert at index 1
print(tasks)
# Output: ['Review Chapter 3', 'Read list documentation', 'Start Chapter 4', 'Practice list operations', 'Take a break']
Remove elements:
Use remove()
to remove the first occurrence of a value, or del
to remove by index.
tasks.remove("Take a break") # Remove by value
print(tasks)
# Output: ['Review Chapter 3', 'Read list documentation', 'Start Chapter 4', 'Practice list operations']
del tasks[0] # Remove the item at index 0
print(tasks)
# Output: ['Read list documentation', 'Start Chapter 4', 'Practice list operations']
Iterate through a list:
Use a for
loop to process each item in the list.
print("\nRemaining tasks:")
for task in tasks:
print(f"- {task}")
# Output:
# Remaining tasks:
# - Read list documentation
# - Start Chapter 4
# - Practice list operations
Tuples are ordered, immutable collections. Once created, their contents cannot be changed. They are often used for fixed collections of items, like coordinates or RGB color values.
Create a tuple:
Tuples are defined using parentheses ()
.
point = (10, 20) # Represents an (x, y) coordinate
rgb_color = (255, 0, 0) # Red color
print(f"Point coordinates: {point}")
# Output: Point coordinates: (10, 20)
print(f"RGB Color: {rgb_color}")
# Output: RGB Color: (255, 0, 0)
Access elements: Access elements just like lists, using indexing.
x_coordinate = point[0]
red_value = rgb_color[0]
print(f"X coordinate: {x_coordinate}")
# Output: X coordinate: 10
print(f"Red value: {red_value}")
# Output: Red value: 255
Immutability: Trying to change an element in a tuple results in an error. This is a defining feature.
# This line will cause an error:
# point[0] = 15
# TypeError: 'tuple' object does not support item assignment
Immutability makes tuples reliable for representing data that shouldn't change accidentally. They can also be used as keys in dictionaries (unlike lists).
Dictionaries store data as key-value pairs. They are unordered (in older Python versions) or insertion-ordered (in newer Python versions) and mutable. Keys must be unique and immutable (like strings, numbers, or tuples). Dictionaries provide fast lookups based on the key.
Create a dictionary:
Use curly braces {}
with key: value
pairs.
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
print(student_scores)
# Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
Access values:
Use the key inside square brackets []
to get the corresponding value.
bob_score = student_scores["Bob"]
print(f"Bob's score: {bob_score}")
# Output: Bob's score: 92
Trying to access a key that doesn't exist will raise a KeyError
. You can use the .get()
method for safer access, which returns None
(or a specified default) if the key is not found.
david_score = student_scores.get("David") # Key doesn't exist
print(f"David's score: {david_score}")
# Output: David's score: None
david_score_default = student_scores.get("David", "Not found") # With default
print(f"David's score: {david_score_default}")
# Output: David's score: Not found
Add or modify entries: Assign a value to a new key to add it, or assign a new value to an existing key to modify it.
# Add a new student
student_scores["David"] = 88
print(student_scores)
# Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
# Update Alice's score
student_scores["Alice"] = 87
print(student_scores)
# Output: {'Alice': 87, 'Bob': 92, 'Charlie': 78, 'David': 88}
Remove entries:
Use del
to remove an entry by key.
del student_scores["Charlie"]
print(student_scores)
# Output: {'Alice': 87, 'Bob': 92, 'David': 88}
Iterate through a dictionary: You can iterate through keys, values, or key-value pairs (items).
print("\nStudent Scores:")
# Iterate through keys (default iteration)
for student in student_scores:
print(f"- {student}: {student_scores[student]}")
print("\nUsing .items():")
# Iterate through key-value pairs
for student, score in student_scores.items():
print(f"- {student} scored {score}")
# Output:
# Student Scores:
# - Alice: 87
# - Bob: 92
# - David: 88
#
# Using .items():
# - Alice scored 87
# - Bob scored 92
# - David scored 88
Sets are unordered collections of unique, immutable items. They are useful for membership testing, removing duplicates, and performing mathematical set operations.
Create a set:
Use curly braces {}
or the set()
function. Note that {}
creates an empty dictionary, so use set()
for an empty set.
# From a list with duplicates
tags_list = ["python", "data", "web", "python", "data"]
unique_tags = set(tags_list)
print(unique_tags)
# Output: {'data', 'python', 'web'} (Order may vary)
# Direct creation
allowed_users = {"alice", "bob", "charlie"}
print(allowed_users)
# Output: {'charlie', 'alice', 'bob'} (Order may vary)
Add elements:
Use the add()
method. Duplicates are automatically ignored.
allowed_users.add("david")
print(allowed_users)
# Output: {'charlie', 'david', 'alice', 'bob'}
allowed_users.add("alice") # Adding existing element has no effect
print(allowed_users)
# Output: {'charlie', 'david', 'alice', 'bob'}
Membership testing:
Use the in
operator to check if an element exists in the set. This is very efficient.
if "bob" in allowed_users:
print("Bob is an allowed user.")
else:
print("Bob is not allowed.")
# Output: Bob is an allowed user.
if "eve" in allowed_users:
print("Eve is an allowed user.")
else:
print("Eve is not allowed.")
# Output: Eve is not allowed.
Set operations:
Sets support operations like union (|
), intersection (&
), difference (-
), and symmetric difference (^
).
admin_users = {"alice", "eve"}
# Union: all users in either set
all_users = allowed_users | admin_users
print(f"All users: {all_users}")
# Output: All users: {'eve', 'charlie', 'david', 'alice', 'bob'}
# Intersection: users in both sets
common_users = allowed_users & admin_users
print(f"Common users (admins who are allowed): {common_users}")
# Output: Common users (admins who are allowed): {'alice'}
# Difference: users in allowed_users but not in admin_users
non_admin_allowed = allowed_users - admin_users
print(f"Allowed users who are not admins: {non_admin_allowed}")
# Output: Allowed users who are not admins: {'charlie', 'david', 'bob'}
Imagine you need to store information about books in a library catalog.
books_by_isbn = {"978-0134": "Python Crash Course", ...}
. This allows quick lookup by ISBN.borrow_history = ["Python Crash Course", "Fluent Python", ...]
. Order matters, and the list can grow as more books are borrowed.rare_book_isbns = {"978-...", "978-..."}
. Checking isbn in rare_book_isbns
is fast.This practical session covered creating, accessing, modifying, and iterating through lists, tuples, dictionaries, and sets. Experimenting with these examples is the best way to become comfortable using Python's collection types effectively. Remember to consider the characteristics of each type. order, mutability, uniqueness, key-value mapping. when deciding which one to use for your specific data organization needs.
© 2025 ApX Machine Learning