By the end of this lesson, you will be able to select and use Python's four core data structures—lists, dictionaries, sets, and tuples—to store and manipulate data efficiently in analytics workflows.
What it is
Python provides four primary built-in data structures for organizing collections of items. Lists are ordered, mutable sequences that allow duplicate values. Tuples are ordered, immutable sequences, often used for fixed records like coordinates or database rows. Dictionaries are unordered (in older versions) or insertion-ordered (Python 3.7+) key-value pairs, ideal for mapping identifiers to data. Sets are unordered collections of unique elements, perfect for membership testing and removing duplicates. Understanding these structures is fundamental because they form the backbone of data cleaning, transformation, and aggregation tasks in libraries like Pandas and NumPy.Why it matters
- Efficiency: Sets provide O(1) average-time complexity for membership checks, making them faster than lists for large datasets.
- Data Integrity: Tuples ensure that critical configuration parameters or record keys cannot be accidentally modified.
- Flexibility: Dictionaries allow rapid lookup by name or ID rather than index, simplifying code readability.
- Cleaning: Lists and sets are essential for filtering out nulls, removing duplicates, and reshaping raw data arrays.
Syntax or steps
To create a list, use square brackets:[item1, item2]. For a tuple, use parentheses: (item1, item2). A dictionary uses curly braces with colons separating keys and values: {key1: value1}. A set uses curly braces without colons: {item1, item2}. Note that an empty set must be created using set(), as {} creates an empty dictionary.
Example
# Define different data structures
user_ids = [101, 102, 103, 101] # List: allows duplicates, mutable
coordinates = (45.5, -122.6) # Tuple: immutable, ordered
user_profiles = { # Dict: key-value mapping
101: "Alice",
102: "Bob"
}
unique_visitors = set(user_ids) # Set: removes duplicates automatically
# Operations
print(f"Original IDs: {user_ids}")
print(f"Unique Visitors: {unique_visitors}")
print(f"Alice's Profile: {user_profiles[101]}")
# Attempting to modify a tuple raises an error
try:
coordinates[0] = 46.0
except TypeError as e:
print(f"Error modifying tuple: {e}")
Explanation: The list user_ids stores raw event data including duplicates. We convert it to a set unique_visitors to instantly identify distinct users. The dictionary user_profiles maps user IDs to names for quick lookup. Finally, we demonstrate that tuples are immutable by attempting to change a coordinate, which triggers a TypeError.
Common mistakes
- Using lists for membership tests: Checking if an item exists in a large list (
x in my_list) is slow (O(n)). Use a set instead for O(1) speed. - Modifying a list while iterating: This causes skipped elements or errors. Iterate over a copy (
for x in my_list[:]) or build a new list. - Confusing empty dict and set: Remember that
{}is an empty dictionary. Useset()to initialize an empty set. - Assuming order in dicts/sets: While dicts preserve insertion order in modern Python, sets do not guarantee any specific order. Do not rely on set indexing.
When to use it
| Structure | Best For | Key Characteristic |
|---|---|---|
| List | Ordered sequences, stacks, queues | Mutable, allows duplicates |
| Tuple | Fixed records, function returns, dict keys | Immutable, hashable |
| Dict | Lookups by name/ID, JSON-like data | Key-value pairs, fast access |
| Set | Uniqueness, mathematical operations | No duplicates, fast membership |
Practice
Guided Exercise: Create a list of numbers[1, 2, 2, 3, 4, 4, 5]. Convert it to a set to remove duplicates, then back to a sorted list. Print the result.
Challenge: Given a dictionary
{"a": 1, "b": 2}, write code to swap the keys and values so that the output is {1: "a", 2: "b"}. Hint: Use a dictionary comprehension.
Quick check
Question: Which data structure would you choose to store a collection of email addresses where you need to quickly check if an address has already been processed?Answer: A set, because it ensures uniqueness and provides very fast membership testing compared to a list.