KAHIBARO Bookshelves
Discord Login Register

8.5. Choosing the right data structure

Why Choosing the Right Data Structure Matters

In many programs, the choice of data structure affects:

  • How easy your code is to write and understand
  • How fast your program runs
  • How simple it is to add new features later

Python gives you several built-in data collections:

  • list
  • tuple
  • dict (dictionary)
  • set

Here you’ll focus on how to decide which one to use, not on their basic syntax.

Think of data structures like different containers:

  • A backpack
  • A toolbox with labeled drawers
  • A safe with a locked combination
  • A basket that ignores duplicates

They all hold “stuff,” but each is better for different situations.

Key Questions to Help You Choose

When deciding which data structure to use, ask yourself:

  1. Do I care about order?
  2. Will the data change (add/remove items)?
  3. Do I need to look things up by a number position or by a name/key?
  4. Can there be duplicates, or must all items be unique?
  5. Do I need a fixed “record” that represents one thing (like a user or product)?
  6. Do I want to prevent accidental modification?

Your answers will guide you to lists, tuples, dictionaries, or sets.

When to Use a List

Use a list when you think: “I have a sequence of items, in order, that might change.”

Typical situations:

  • A to-do list of tasks:
    • Order matters (task 1, task 2, …)
    • You might add or remove tasks
  • A list of scores in a game:
    • You may sort them, append new scores
  • A list of user inputs:
    • You gather values over time

Good signs you want a list:

  • You say “the first, second, third…” item
  • You want to loop in order: for item in items:
  • You want to add/remove items often: append, pop, remove, insert
  • You often use indexes: items[0], items[1]

Example use cases:

  • Shopping cart items in an online store:
  cart_items = ["apple", "banana", "chocolate"]
  • Recent search queries:
  recent_searches = ["python list tutorial", "best laptop", "weather today"]

If your main question is “What’s the item at position N?”, a list is usually the first choice.

When to Use a Tuple

Use a tuple when you think: “I have a small fixed collection of values that belong together and should not change.”

Tuples are good for records: one thing with several fields.

Typical situations:

  • Representing a 2D coordinate:
  point = (10, 20)   # x, y
  • Representing a date as (year, month, day):
  birthday = (1995, 7, 30)
  • Returning multiple values from a function

Good signs you want a tuple:

  • The number of items is fixed and meaningful together
  • You don’t want code elsewhere to accidentally change them
  • You use them as keys in a dictionary (requires immutability)

Compare:

  • List (changeable collection): colors = ["red", "green", "blue"]
  • Tuple (fixed record): rgb = (255, 200, 150)

If your main thought is “These values form one unchanging thing”, consider a tuple.

When to Use a Dictionary

Use a dict when you think: “I want to look up values by a name or key, not by position.”

Dictionaries are like labeled drawers: each value has a label (key).

Typical situations:

  • Storing a user profile:
  user = {
      "username": "alice",
      "age": 30,
      "email": "alice@example.com"
  }
  • Counting how many times each word appears:
  word_counts = {"python": 3, "code": 5}
  • Storing settings:
  settings = {
      "volume": 80,
      "theme": "dark",
      "notifications": True
  }

Good signs you want a dictionary:

  • You care about meaningful names for each value
  • You say “look up X by its name or id”
  • You don’t want to remember a position number; you want to use a key:
    • user["email"] is clearer than user[2]
  • You might add new fields later without breaking code

If your main question is “What is the value for this key?”, choose a dictionary.

When to Use a Set

Use a set when you think: “I want a collection that automatically ignores duplicates and cares only about membership, not order.”

Sets are like bags where:

  • Each item can appear at most once
  • Order is not guaranteed

Typical situations:

  • Keeping track of unique items:
    • Unique visitors to a website
    • Unique tags on a blog
  • Checking membership quickly:
    • “Is this item in the allowed list?”
  • Doing set operations:
    • Union, intersection, difference

Example:

visited_pages = {"home", "about", "contact"}
if "blog" not in visited_pages:
    print("User has not visited the blog page yet")

Good signs you want a set:

  • You say “unique list of …”
  • Order doesn’t matter
  • You often ask: “Is X in this collection?” (in checks)

If your main question is “Is this item present, and I don’t care about duplicates or order?”, use a set.

Comparing Data Structures by Common Needs

Here’s a quick comparison based on typical needs:

1. Do you need to keep the order?

  • Yes, order matters:
    • Use list (usually)
    • tuple for fixed ordered records
  • No, order doesn’t matter:
    • Use set (for unique items)
    • Use dict when you care about key-value pairs (modern Python keeps insertion order, but dicts are mainly for key lookups)

2. Will the contents change?

  • Will change (add/remove/edit):
    • list, dict, set
  • Should stay the same (fixed):
    • tuple (good for constants or records that shouldn’t change)

3. Do you need named fields?

  • Yes, named fields:
    • Use dict:
      • user["age"] instead of user[1]
  • No, just a sequence:
    • list (if changeable or long)
    • tuple (if fixed-size record)

4. Are duplicates allowed?

  • Duplicates allowed:
    • list, tuple
  • No duplicates:
    • set (for just values)
    • Keys in a dict are also unique (values don’t have to be)

5. What’s the main operation?

  • Access by position (items[0], items[1]):
    • list or tuple
  • Access by key/name (profile["email"]):
    • dict
  • Check if something exists (if x in collection:) without worrying about order:
    • set (best), or dict keys

Real-World Scenario Examples

Example 1: Students in a class

You’re storing information about students.

You might use:

  • A list of student names (order maybe doesn’t matter, but duplicates might be ok):
  students = ["Alice", "Bob", "Charlie"]
  • A dict for a single student’s details:
  student = {
      "name": "Alice",
      "age": 20,
      "id": "S123",
      "grade": "A"
  }
  • A set of student IDs to quickly check uniqueness:
  student_ids = {"S123", "S456", "S789"}
  • A tuple for a fixed record like (name, age, id):
  alice = ("Alice", 20, "S123")

Here you might combine several structures:

  • A list of dictionaries:
  students = [
      {"name": "Alice", "age": 20, "id": "S123"},
      {"name": "Bob", "age": 21, "id": "S124"},
  ]

Example 2: Settings for an application

You’re storing app settings that can be changed during runtime:

  • Use a dict:
  settings = {
      "theme": "dark",
      "volume": 70,
      "language": "en"
  }

Why dict?

  • You want to look up by setting name ("theme", "volume")
  • You may add new settings later

A list like ["dark", 70, "en"] is less clear: what does each position mean?

Example 3: Tags on blog posts

You have tags such as "python", "learning", "beginner".

  • Use a set for tags per post:
  tags = {"python", "learning", "beginner"}
  • If a user adds "python" again, the set still has only one "python"

If you need to store posts with their tags:

post = {
    "title": "Learning Python",
    "tags": {"python", "learning", "beginner"}
}

Here you combine a dict (for named fields) and a set (for unique tags).

Example 4: Ordered steps in a recipe

A recipe has steps that must be followed in order:

  • Use a list:
  steps = [
      "Preheat the oven to 180°C",
      "Mix flour and sugar",
      "Add eggs",
      "Bake for 25 minutes"
  ]

You might insert a new step or change one, so a list is more flexible than a tuple here.

Simple Decision Guide

You can use this as a quick mental checklist:

  1. Is this a sequence of items, possibly with duplicates, where order matters?
    → Use a list.
  2. Is this a small, fixed-size “record” that forms one unit and should not change?
    → Use a tuple.
  3. Do I need to map names/keys to values (like a mini-database of properties)?
    → Use a dict.
  4. Do I only care about unique items and quick membership tests, not order?
    → Use a set.
  5. Do I need a combination?
    • Lists of dictionaries
    • Dictionaries with sets inside
    • Lists of tuples
      Often, real programs use several data structures together.

Practicing Choosing Data Structures

To get better at this, practice by:

  • Taking a real-world object (book, user, product, event) and deciding:
    • Should it be a dict, a tuple, or something else?
  • Looking at a problem and asking:
    • Do I care about order, uniqueness, quick lookup, or fixed records?

Example practice questions (you don’t have to code them now, just think about the choice):

  1. A playlist of songs where order matters and songs can repeat
  2. A product with a name, price, and stock count
  3. A list of all unique countries users are from
  4. Store each user’s username and their list of favorite movies

Your job is to decide:

  • Which data structure (or combination) makes the most sense?
  • Why that choice fits the needs (order, mutability, duplicates, lookup method)?

The more you think this way, the more natural choosing the right data structure will become.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms