Module 6: Data Structures: Lists, Tuples, Sets, Dictionaries

Variables are great for storing single pieces of data. But what happens when you have a list of users, a collection of settings, or a set of unique tags? This module introduces data structures—the containers for your data.

1. Why We Need Data Structures

Imagine you're building a to-do list application. You could create a variable for each task:

task1 = "Buy groceries" task2 = "Finish homework" task3 = "Call mom"

This is clumsy. What if the user adds a fourth task? You can't just create `task4` in your code. You need a way to store a collection of items in a single variable. That's what **data structures** are for. They are specialized formats for organizing, processing, retrieving, and storing data.

🧠 Core Concept: The Filing Cabinet

Think of a data structure as a filing cabinet. Instead of leaving individual papers (data points) all over your desk, you organize them into folders, drawers, and labeled sections. Each type of data structure in Python is like a different kind of filing system, each with its own strengths for certain tasks.

2. Lists: The All-Purpose Workhorse

A **list** is an ordered, changeable collection of items. It's probably the most common data structure you'll use in Python. Lists are great when you need to store items in a specific sequence and expect to add, remove, or change items later.

Creating and Accessing Lists

You create a list by placing items inside square brackets `[]`, separated by commas. To access an item, you use its **index**—its position in the list. Indexing in Python starts at **0**.

# A list of strings fruits = ["apple", "banana", "cherry"] # Accessing items by index print(f"The first fruit is: {fruits[0]}") # Output: apple print(f"The third fruit is: {fruits[2]}") # Output: cherry # You can also use negative indexing to start from the end print(f"The last fruit is: {fruits[-1]}") # Output: cherry

Modifying Lists

Because lists are mutable, you can easily change them.

shopping_list = ["milk", "eggs", "bread"] # Change an item shopping_list[1] = "butter" print(f"Updated list: {shopping_list}") # Add an item to the end shopping_list.append("juice") print(f"Added juice: {shopping_list}") # Remove an item shopping_list.remove("milk") print(f"Removed milk: {shopping_list}")

3. Tuples: The Immutable Protectors

A **tuple** is an ordered, unchangeable collection of items. It's very similar to a list, but with one critical difference: once you create a tuple, you cannot change it. This property is called **immutability**.

Creating and Using Tuples

You create a tuple using parentheses `()`. You access items just like with a list, but you can't assign a new value to an index.

# A tuple of coordinates point = (10, 20) print(f"The x-coordinate is: {point[0]}") # This line would cause an error! # point[0] = 15 # TypeError: 'tuple' object does not support item assignment

Why use a tuple? Tuples are useful for data that should not be modified, like coordinates, configuration settings, or database records. They are also slightly more memory-efficient than lists.

4. Sets: The Unique and Unordered

A **set** is an unordered, mutable collection of **unique** items. Its primary characteristics are that it does not allow duplicate elements and it doesn't maintain any specific order.

Creating and Using Sets

You create a set using curly braces `{}` or the `set()` function. Their main superpower is enforcing uniqueness.

# A list with duplicates numbers = [1, 2, 2, 3, 4, 4, 4, 5] # Convert the list to a set to get unique items unique_numbers = set(numbers) print(f"Unique numbers: {unique_numbers}") # Output might be {1, 2, 3, 4, 5} (order not guaranteed) # You can add and remove items unique_numbers.add(6) unique_numbers.remove(2) print(f"Modified set: {unique_numbers}")

Sets are excellent for membership testing (checking if an item is present) and for mathematical set operations like union and intersection.

5. Dictionaries: The Key-Value Store

A **dictionary** is an unordered (in Python versions before 3.7), mutable collection of **key-value pairs**. Instead of accessing items by a numerical index, you access them by a unique **key**. This is like a real-world dictionary where you look up a word (the key) to find its definition (the value).

Creating and Using Dictionaries

You create a dictionary using curly braces `{}`, with each key-value pair written as `key: value`.

# A dictionary representing a user user = { "name": "Alice", "age": 30, "is_admin": False } # Access a value by its key print(f"User's name: {user['name']}") # Change a value user["age"] = 31 # Add a new key-value pair user["city"] = "New York" print(f"Updated user data: {user}")

Dictionaries are incredibly useful for storing structured information where you need to look up values quickly without knowing their position.

6. Quick Summary Table

Characteristic List Tuple Set Dictionary
Syntax `[1, 2, 3]` `(1, 2, 3)` `{1, 2, 3}` `{'a': 1, 'b': 2}`
Ordered ✅ Yes ✅ Yes ❌ No ✅ Yes (since Py 3.7)
Mutable ✅ Yes ❌ No ✅ Yes ✅ Yes
Allows Duplicates ✅ Yes ✅ Yes ❌ No ✅ Yes (values), ❌ No (keys)

You've Completed Module 6!

Amazing! You've just learned about the four fundamental data structures in Python. Understanding when to use a list, tuple, set, or dictionary is a key skill that separates beginner and intermediate programmers.

Now that you can store data in collections, our next module will focus on mastering a specific data type that's everywhere: strings. We'll also learn how to make our programs save and load data from files.

On to Module 7: Strings & File I/O →