Chapter 4 of 11
Collections of Data: Lists, Tuples, and Dictionaries
Instead of juggling single values, discover how to organize groups of items—like shopping lists, scores, or user records—so Python can manage them effortlessly. You’ll learn the building blocks that power almost every real-world Python program.
Why We Need Collections of Data
From Single Values to Groups
So far, you used single values like one number or one word. Real problems usually need groups of values, like all items in a shopping cart or scores of all players.
Python Collections
Instead of many separate variables, Python gives you collections that hold many values together. In this module you will meet lists, tuples, and dictionaries.
What You Will Learn
You will learn to create and change lists, explain how tuples differ from lists, and use dictionaries to store and read key–value data like user profiles.
First Steps With Lists
A list is an ordered collection of items. You write a list with square brackets `[]`, and items are separated by commas.
Here is how to create and use a simple shopping list:
```python
Create a list of strings
shopping_list = ["milk", "bread", "eggs"]
print(shopping_list)
print("Number of items:", len(shopping_list))
Access items by index (positions start at 0)
print("First item:", shopping_list[0])
print("Second item:", shopping_list[1])
print("Last item:", shopping_list[2])
Change an item
shopping_list[1] = "brown bread"
print("Updated list:", shopping_list)
```
Run this code and watch:
- How the list is printed
- How `len()` tells you how many items are inside
- How changing one position updates the list
Indexes and Negative Indexes
What Is an Index?
Lists are ordered, so each item has a position called an index. The first item has index 0, the second has index 1, the third has index 2, and so on.
Negative Indexes
Python also has negative indexes. Index -1 means the last item, -2 means the second-to-last, and so on, which is handy to reach the end of a list.
Index Example
For `numbers = [10, 20, 30, 40, 50]`, `numbers[0]` is 10, `numbers[2]` is 30, `numbers[-1]` is 50, and `numbers[-2]` is 40.
Common List Methods: append, insert, pop
Lists are mutable, which means you can change them after you create them. Here are three very common list methods:
- `append(item)` – add an item to the end of the list
- `insert(index, item)` – add an item at a specific position
- `pop(index)` – remove and return the item at a position (by default, removes the last item)
Try this code:
```python
friends = ["Alex", "Jordan", "Taylor"]
print("Start:", friends)
1. Add to the end
friends.append("Sam")
print("After append:", friends)
2. Insert at position 1
friends.insert(1, "Riley")
print("After insert at index 1:", friends)
3. Remove last item with pop()
last_friend = friends.pop()
print("Popped:", last_friend)
print("After pop:", friends)
4. Remove by index (position 0)
first_friend = friends.pop(0)
print("Removed first:", first_friend)
print("Final list:", friends)
```
Watch how the list changes step by step.
Practice: Fix the List
Try this thought exercise. You do not need to run code, but you can if you want.
You start with this list of tasks:
```python
tasks = ["wake up", "brush teeth", "go to school"]
```
You want the list to become:
```python
["wake up", "brush teeth", "eat breakfast", "go to school", "do homework"]
```
Your challenge: Write the Python lines (in your head or on paper) to:
- Add "eat breakfast" between "brush teeth" and "go to school".
- Add "do homework" to the end of the list.
Hints:
- Use `insert(index, item)` to put something in the middle.
- Use `append(item)` to add something at the end.
Check yourself:
A possible solution is:
```python
tasks.insert(2, "eat breakfast")
tasks.append("do homework")
```
Think: Why is the index `2` for "eat breakfast"?
Tuples: Lists You Cannot Change
What Is a Tuple?
A tuple is like a list but uses parentheses `()` and cannot be changed after it is created. This is different from lists, which are changeable.
Tuple Example
For example: `colorstuple = ("red", "green", "blue")`. You can read `colorstuple[0]`, but trying `colors_tuple[0] = "yellow"` causes a TypeError.
When Tuples Are Useful
Use tuples when data should stay fixed, like days of the week or coordinates: `point = (3, 5)`. You can unpack with `x = point[0]`, `y = point[1]`.
Quick Check: Lists vs Tuples
Test your understanding of lists and tuples.
Which statement is correct?
- Lists and tuples are both changeable.
- Lists are changeable, tuples are not.
- Tuples use [], lists use ().
- You cannot use indexes with tuples.
Show Answer
Answer: B) Lists are changeable, tuples are not.
Lists are mutable (changeable), while tuples are immutable (not changeable). Tuples use (), lists use []. Both support indexing.
Dictionaries: Storing Key–Value Pairs
What Is a Dictionary?
A dictionary stores key–value pairs. Instead of using positions like 0 or 1, you use a key (often a string) to look up a value.
Dictionary Example
Example: `user = {"name": "Aisha", "age": 15, "email": "aisha@example.com"}`. Keys are "name", "age", "email"; values are the data for each key.
Access and Update
Use `user["name"]` to read a value. Add or change values with `user["grade"] = 10` or `user["email"] = "new@example.com"`.
Iterating Over Dictionary Keys and Values
You often want to loop through everything in a dictionary.
Useful patterns:
- `for key in dict:` – loop over keys
- `for key, value in dict.items():` – loop over keys and values together
Example:
```python
user = {
"name": "Aisha",
"age": 15,
"email": "aisha@example.com"
}
print("Keys only:")
for key in user:
print(key)
print("\nKeys and values:")
for key, value in user.items():
print(key, "->", value)
```
This will show each key and the value it points to, like a small table.
Mini Design Challenge: Choose the Right Collection
For each situation, decide whether a list, tuple, or dictionary fits best. Think first, then check suggested answers.
- You want to store the 3D coordinates of a point: x, y, z.
- You want to store all the scores from a test for 30 students, but you do not care about names, just the numbers.
- You want to store information about a book: title, author, year, and ISBN.
- You want to store the days of the week, which never change.
Suggested answers:
- Tuple – a small, fixed group of related numbers.
- List – an ordered, changeable sequence of scores.
- Dictionary – key–value pairs like `"title"`, `"author"`, etc.
- Tuple (or list) – but tuple makes sense because the days do not change.
Review: Key Terms
Use these flashcards to review the main ideas from this module.
- List
- An ordered, mutable collection of items written with square brackets [], like [1, 2, 3]. You can change, add, and remove items.
- Tuple
- An ordered, immutable collection of items written with parentheses (), like (1, 2, 3). Once created, it cannot be changed.
- Dictionary
- A collection of key–value pairs written with curly braces {}, like {"name": "Aisha", "age": 15}. You access values by key, not by index.
- Index
- The position of an item in a list or tuple. The first item has index 0. Negative indexes like -1 start from the end.
- append()
- A list method that adds a new item to the end of a list, for example: my_list.append("new").
- insert()
- A list method that adds a new item at a specific position: my_list.insert(index, item). Existing items move to the right.
- pop()
- A list method that removes and returns an item. With no index it removes the last item; with an index it removes that position.
- Key–value pair
- A pair in a dictionary that links a key (like "email") to a value (like "a@b.com"). You get the value with dict["email"].
Key Terms
- pop
- A list method that removes and returns an item by index (or the last item if no index is given).
- list
- An ordered, mutable collection of items written with square brackets [], such as ["apple", "banana"].
- index
- The position of an item in a list or tuple. Python uses zero-based indexing, so the first item is at index 0.
- tuple
- An ordered, immutable collection of items written with parentheses (), such as (1, 2, 3). Its contents cannot be changed after creation.
- append
- A list method that adds an item to the end of a list: my_list.append(item).
- insert
- A list method that adds an item at a specific index: my_list.insert(index, item).
- mutable
- Describes an object that can be changed after it is created, like a list or dictionary.
- immutable
- Describes an object that cannot be changed after it is created, like a tuple or a string.
- dictionary
- A collection of key–value pairs written with curly braces {}, such as {"name": "Sam", "age": 14}. Values are accessed by key.
- key–value pair
- A pair in a dictionary where a key refers to a value, for example "age": 15.