Lesson 8.4: Choosing the Right Data Structure
What You'll Learn
- How to compare lists, tuples, and dictionaries
- Key differences in mutability, ordering, and access patterns
- Guidelines for choosing the best data structure
- Real-world examples that demonstrate when to use each type
- Performance considerations for beginners
1. Quick Comparison
| Feature | List | Tuple | Dictionary |
|---|---|---|---|
| Syntax | [1, 2, 3] |
(1, 2, 3) |
{"a": 1} |
| Ordered? | Yes | Yes | Yes (Python 3.7+) |
| Mutable? | Yes | No | Yes |
| Duplicates? | Allowed | Allowed | Keys: No, Values: Yes |
| Access by | Index (int) | Index (int) | Key (any immutable) |
| Best for | Collections that change | Fixed collections | Labeled / mapped data |
2. When to Use a List
Use a list when you have an ordered collection of similar items that may need to grow, shrink, or be rearranged.
Good Use Cases for Lists
# Shopping list - items get added and removed shopping = ["milk", "bread", "eggs"] shopping.append("butter") shopping.remove("bread") # Test scores - need to sort and calculate averages scores = [85, 92, 78, 95, 88] scores.sort() average = sum(scores) / len(scores) # To-do items - order matters, items get completed tasks = ["study", "exercise", "cook dinner"]
Rule of Thumb: If you ask "how many items?" or "what's item number N?" or need to add/remove items, use a list.
3. When to Use a Tuple
Use a tuple when you have a fixed collection that should not change, or when the position of each element has a specific meaning.
Good Use Cases for Tuples
# Coordinates - x and y should not change independently location = (34.05, -118.24) # RGB color values - a color is a fixed set of values red = (255, 0, 0) # Function returning multiple values def get_dimensions(): return (1920, 1080) width, height = get_dimensions() # Days of the week - they never change DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") # Using tuples as dictionary keys grid = { (0, 0): "start", (3, 4): "treasure" }
Rule of Thumb: If the data should never change, if position has meaning (x, y, z), or if you need it as a dictionary key, use a tuple.
4. When to Use a Dictionary
Use a dictionary when you need to look up values by a meaningful label rather than by position.
Good Use Cases for Dictionaries
# Student record - each field has a name student = { "name": "Alice", "id": 12345, "gpa": 3.8 } # Configuration settings config = { "debug": False, "max_retries": 3, "timeout": 30 } # Counting occurrences word_counts = {"hello": 5, "world": 3} # Phone book - look up by name contacts = { "Alice": "555-0101", "Bob": "555-0102" }
Rule of Thumb: If you ask "what is the value for this key?" or need to label your data with meaningful names, use a dictionary.
5. Combining Data Structures
Real programs often combine these structures. Here are common patterns:
# List of dictionaries - a collection of records students = [ {"name": "Alice", "grade": 95}, {"name": "Bob", "grade": 87}, {"name": "Carol", "grade": 92} ] # Find the highest grade best = max(students, key=lambda s: s["grade"]) print(f"Top student: {best['name']} ({best['grade']})") # Dictionary with list values class_roster = { "Math 101": ["Alice", "Bob"], "CS 201": ["Carol", "Dave", "Eve"] } # Add a student to a class class_roster["Math 101"].append("Frank") print(class_roster["Math 101"])
Top student: Alice (95)
['Alice', 'Bob', 'Frank']
6. Decision Flowchart
When choosing a data structure, ask yourself these questions:
How to Decide
- Do I need to look up values by a label/name? → Use a dictionary
- Should the data never change? → Use a tuple
- Do I need to add, remove, or reorder items? → Use a list
- Do I need it as a dictionary key? → Use a tuple (or string/number)
- Does each position have a specific meaning? (like x, y) → Use a tuple
- Is it a collection of similar items? → Use a list
Check Your Understanding
Question: For each scenario, which data structure would you choose?
- Storing the months of the year
- A phone book that maps names to numbers
- A playlist where songs can be added and reordered
- An (x, y) coordinate pair
- Tuple — months never change
- Dictionary — look up numbers by name
- List — songs get added, removed, and reordered
- Tuple — fixed pair where position has meaning
Key Takeaways
- Use lists for ordered, changeable collections of similar items
- Use tuples for fixed data, meaningful positions, or dictionary keys
- Use dictionaries for labeled data and fast lookups by key
- Real programs often combine these structures (lists of dicts, dicts with list values, etc.)
- The right data structure makes your code clearer and easier to maintain