Lists and Dictionaries
How to store data in Python without regretting it later — the standard containers.
So far, every variable you have created holds exactly one value — a number, a string, a boolean. But real programs deal with collections: a list of 1,000 student names, a user profile with name, age, and city, or an API response with hundreds of data points. Managing 1,000 separate variables is like keeping 1,000 loose sticky notes instead of one organized notebook.
Python provides two fundamental collection types: lists for ordered sequences (when position matters) and dictionaries for key-value pairs (when you want to look things up by name). These two structures are so central that nearly every Python program uses at least one of them.
Lists — Ordered Collections with Numbered Slots
Definition
List (list)
Analogy
Definition
The shelf analogy fits well for numbered positions and shifting during insert/remove. It breaks because a real shelf has a fixed number of slots — Python lists grow dynamically. Also, shelf slots have physical size constraints, while Python lists can hold any object, including other lists.
Note
Shopping List Step by Step
- 1. shopping = ["Bread", "Milk", "Apples"] → 3 items at positions 0, 1, 2
- 2. shopping.append("Cheese") → 4 items: [..., "Cheese"] at position 3
- 3. print(shopping[0]) → "Bread"first item = index 0
- 4. shopping.pop(1) → removes "Milk", list: ["Bread", "Apples", "Cheese"]
- 5. "Milk" in shopping → Falseit was removed
Each step shows the list state after the operation. Notice: after pop(1), all elements to the right shift one position to the left.
Caution
Watch Out: IndexError
The index must be between 0 and len(list) - 1 (negative indices like list[-1] count from the end). Accessing beyond these bounds raises an IndexError. Because Python starts at 0, list[3] is the fourth element — not the third.
colors = ["red", "green", "blue"]
print(colors[3]) # IndexError: list index out of range
# Valid indices: 0, 1, 2Dictionaries — Looking Things Up by Name
Definition
Dictionary (dict)
Analogy
Definition
The phone book analogy fits for key-based access. It breaks because a real phone book is alphabetically sorted — Python dicts use hash tables, not alphabetical order. Also, a phone book contains only name-number pairs, while Python dicts can map keys to any value, including nested dicts and lists.
Example: Person Record
person = {"name": "Anna", "age": 28, "city": "Berlin"}
print(person["age"]) # 28
person["job"] = "Engineer" # adds new key-value pair
print(person.get("hobby", "unknown")) # "unknown" (no error)
for key, value in person.items():
print(f"{key}: {value}") # prints all pairsThe .get() call is the safe counterpart to person["hobby"], which would crash with KeyError. Use .get() whenever you're not sure a key exists.
Ordered sequence. Access by index (position). Use lists when order matters: shopping lists, step sequences, collections you iterate through.
Key-value mapping. Access by key (name). Use dicts when you want to look things up by name: user profiles, configurations, word counters.
Caution
Watch Out: KeyError
Accessing dict[key] with a non-existent key raises a KeyError. Use .get(key, default) instead for safe access.
person = {"name": "Anna"}
print(person["hobby"]) # KeyError: 'hobby'
print(person.get("hobby", "unknown")) # "unknown" (no error)Aliasing — When Two Names Share One Object
Definition
Aliasing
Analogy
Definition
The document analogy fits for "two links, one object." It breaks because in real life, sharing a document is a deliberate choice (you send a link), while aliasing in Python happens automatically and silently when you write b = a. Beginners don't realize they're "sharing" the object.
Note
The Aliasing Trap Step by Step
- 1. a = [1, 2, 3] → List with three elements created
- 2. b = a → b is an alias, NOT a copy! Both point to the same list.
- 3. b.append(4) → The list is now [1, 2, 3, 4]
- 4. print(a) → [1, 2, 3, 4] — a changed too! Fix: b = a.copy()
Caution
Aliasing Is Silent and Automatic
b = a does NOT copy. It creates a second name for the same object. Use .copy() for a copy of your own; only nested lists or dicts inside it stay shared. This applies to lists AND dictionaries.
# Alias (NOT copied):
b = a
b.append(4) # also changes a!
# Real copy:
b = a.copy()
b.append(4) # a stays unchangedInteractive: Python Collection Types Compared
You now know lists and dictionaries. But Python has more collection types; the two most important are sets and tuples. Click on a row in the comparison matrix to see the properties and typical use cases of each type. Pay attention to the color coding: green indicates available capabilities, red indicates limitations. Yellow means: neither an advantage nor a drawback, it depends on the use case.
Python Collection Types Compared
Click a row for detail view
| Type | Ordered | Mutable | Duplicates | Access |
|---|---|---|---|---|
| list | ✓ | ✓ | ✓ | Index [i] |
| dict | ✓ | ✓ | ✗ Keys | Key ["k"] |
| set | ✗ | ✓ | ✗ | — |
| tuple | ✓ | ✗ | ✓ | Index [i] |
Guido van Rossum, Python's creator, explained the decision in a 2013 blog post: half-open intervals like a[:n] for the first n elements and a[n:] for the rest work cleanly with 0-based indices, without fiddly +1/-1 corrections. It wasn't a given: Python's predecessor ABC counted from 1, C, the other big influence, from 0. According to Guido, slice notation helped him decide.
A practical benefit: len(list) is always the first invalid index — making boundary checks easy.
JSON (JavaScript Object Notation) is the standard format for web APIs, AI model configurations, and data exchange. When loaded with json.loads(), JSON objects become Python dicts and JSON arrays become Python lists.
import json
api_response = '{"name": "GPT-3", "type": "LLM", "params": [175, "billion"]}'
data = json.loads(api_response)
print(data["name"]) # "GPT-3" (dict access)
print(data["params"][0]) # 175 (nested: dict → list)Understanding lists and dictionaries means understanding the structure of real-world data — from API responses to configuration files.
Note
Key Takeaways
- A list is an ordered, mutable sequence accessed by index (starting at 0). Use lists when order matters — shopping lists, step sequences, collections you iterate through.
- A dictionary is a mutable collection of key-value pairs accessed by key. Use dicts when you want to look things up by name — user profiles, configurations, word counters.
- b = a does not copy a list or dictionary — it creates a second name for the same object. Use a.copy() (for lists also list(a)) for an independent copy.
- Common traps: IndexError (accessing beyond list length), KeyError (accessing a missing dict key — use .get()), off-by-one errors from 0-based indexing.
- JSON — the format for web APIs and AI services — maps directly to Python dictionaries and lists. Understanding these two types means understanding the shape of real-world data.
Check
Quiz: Lists and Dictionaries
What does colors[1] return if colors = ["red", "green", "blue"]?
Select one answer
1. What does colors[1] return if colors = ["red", "green", "blue"]?
2. person = {"name": "Anna", "age": 28}. What does person.get("hobby", "unknown") return?
3. a = [1, 2, 3]; b = a; b.append(4). What is a now?
4. You want to store 500 user profiles (each with name, email, age). Which structure fits best?
Check
Checkpoint: Do You Understand Lists and Dictionaries?
Can you explain this in your own words? Tick what you've got.
0 of 3 done