← Back to modules

Module

Data Structures

How do you organize data in an effective way? We will compare lists, tuples, sets, and dictionaries so you can choose the right structure for each problem.

1. lists

Lists: Ordered and Flexible

A list stores an ordered sequence of values, which means every item has a position called an index. In Python, indexing starts at 0, so the first item is at position 0, the second at 1, and so on. Lists are mutable, so you can add, remove, and replace items after creation.

Lists are a strong default when order matters and your data may grow or change over time. They are ideal for to-do lists, queues, shopping carts, and any situation where you need a collection that can change while still keeping order.

A practical way to think about lists is: use a list when you need a row of items you can edit. If you need the last item quickly, Python also supports negative indexes, where -1 means the last element.

Python list example

students = ["Ada", "Grace", "Linus"]
students.append("Katherine")
first_student = students[0]
last_student = students[-1]

Select an index to see which value is returned from the list.

["Ada", "Grace", "Linus", "Katherine", "Margaret"]

Choose an index to reveal a value.


2. tuples and mutability

Tuples and Mutability

A tuple is ordered like a list, but it is immutable. After creation, tuple elements cannot be changed, removed, or appended. This immutability helps you protect data that should stay fixed.

This makes tuples useful for fixed records, such as coordinates, RGB color values, or settings that should not be edited by accident. Lists remain better for collections that need frequent updates.

A simple rule is: if the collection should change, use a list; if the collection should stay the same, use a tuple. That choice communicates intent clearly to anyone reading your code.

List vs tuple in Python

coordinates = (40.7, -74.0)   # tuple (immutable)
queue = ["task-1", "task-2"]   # list (mutable)
queue.append("task-3")

3. sets and dictionaries

Sets and Dictionaries

A setstores unique values only. If you try to add a duplicate value, the set keeps a single copy. Sets are useful for fast membership checks, such as asking "is this user ID already in the system?" many times.

A dictionary stores key-value pairs, letting you find values by key quickly. Instead of searching a list for a name, you can directly ask for the value using the key, like student["name"].

Choose a set when uniqueness matters. Choose a dictionary when labels or identifiers map to data. Both are foundational structures in real software because they make lookup operations much faster and clearer.

Set and dictionary examples

tags = {"python", "cs", "python"}  # duplicate removed
student = {"name": "Ada", "age": 20}
knows_python = "python" in tags
student_name = student["name"]

First, click a key to retrieve its value. Then solve the challenge by naming the key for a given value.

Key lookup

dictionary["language"] returns python.

Challenge: find the key

Which key maps to the value beginner?


4. differences and use cases

How They Differ and When to Use Each

The right structure depends on what your program needs: order, uniqueness, mutability, or key-based access. If you pick a structure that matches your goal, your code becomes easier to read and easier to maintain.

  • List: ordered, mutable, allows duplicates. Best when you need a changeable sequence.
  • Tuple: ordered, immutable, allows duplicates. Best for fixed records.
  • Set: unordered conceptually, mutable, unique values only. Best for membership checks and deduplication.
  • Dictionary: key-value mapping, mutable, unique keys. Best when you need label-based lookups.

A useful decision pattern is: first ask "how will I access the data most often?" If the answer is by position, choose list or tuple. If by label, choose dictionary. If by existence only, choose set.

Question 1 of 5

You need to keep the exact order of student names and allow duplicates. Which structure is the best fit?


5. performance

Performance Differences

Big collections make performance more visible. Lists usually require scanning to find a value, while sets and dictionaries use hashing for fast average lookup.

In practical terms: if you repeatedly ask "does this item exist?", sets and dictionary keys are often faster than lists.

This does not mean lists are bad. Lists are still perfect when order and index-based access are your priority. The key idea is matching structure to the operation you do most often.

Rule of thumb

Use lists for ordered sequences, tuples for fixed records, sets for unique membership checks, and dictionaries for labeled lookups.


6. mixing structures

Mix Structures to Model Real Data

Real programs often combine structures. For example, a classroom app may use a dictionary from class name to a list of students, plus a set of unique student IDs.

This is common in production software: one structure handles organization, another handles uniqueness, and another handles fixed details. Mixing structures lets you model real-world data cleanly without forcing one tool to do every job.

If a data model feels confusing, simplify it by describing each part in plain words first, then choose the matching structure. That approach helps avoid overcomplicated designs.

Combined structure example

classes = {
    "cs101": ["Ada", "Grace"],
    "cs102": ["Linus", "Katherine"],
}
student_ids = {1001, 1002, 1003, 1004}
lab_seat = (3, 5)  # fixed row/column tuple

7. guided project

Critical Thinking Quiz

Apply what you learned by choosing the best structure for each scenario. Aim for a full score, then revisit sections where your reasoning needs work.

Do not treat this as memorization. Before choosing an answer, ask what the scenario needs most: order, mutability, uniqueness, or key lookup. That reasoning process is exactly what developers use in real projects.

If you miss a question, read the explanation and connect it back to the section concept. Repeating this cycle builds strong intuition and reduces mistakes when you design your own programs.

Question 1 of 5

A shopping cart stores products in the order users add them, and products can repeat. Which structure should back this cart?