Why Lists and Dictionaries Matter for “Storing and Updating”
In real programs, you rarely store just one value. You store collections of related values (like a shopping list) and you update them over time (add items, remove items, change quantities). Python gives you two beginner-friendly tools for this: lists and dictionaries.
A list stores items in a specific order. You usually use a list when the position (index) matters or when you want to keep duplicates (two identical items can exist).
A dictionary stores pairs of keys and values. You usually use a dictionary when you want to look up data by a name/label (the key), like looking up a phone number by a contact name.
This chapter focuses on how to create, read, and especially update data in lists and dictionaries, because updating is what turns a static script into something useful.
Lists: A Container for Ordered Data
Creating Lists
You create a list using square brackets []. Items are separated by commas.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
tasks = ["email Alex", "buy milk", "study Python" ]Lists can hold different types of items, but beginners often keep them consistent (all strings, all numbers) to avoid confusion.
prices = [2.50, 10.00, 3.99]Reading Items: Indexing and Slicing
Each item in a list has an index (position). Indexes start at 0.
tasks = ["email Alex", "buy milk", "study Python"]
first_task = tasks[0] # "email Alex"
last_task = tasks[2] # "study Python"You can also count from the end using negative indexes.
last_task = tasks[-1] # "study Python"A slice gives you a new list containing a range of items.
tasks = ["email Alex", "buy milk", "study Python", "clean desk"]
first_two = tasks[0:2] # ["email Alex", "buy milk"]
from_second = tasks[1:] # ["buy milk", "study Python", "clean desk"]Updating Lists: Changing an Existing Item
To update an item, assign a new value to a specific index.
tasks = ["email Alex", "buy milk", "study Python"]
tasks[1] = "buy oat milk"
# tasks is now ["email Alex", "buy oat milk", "study Python"]This is one of the simplest “update” operations: keep the list structure, but replace a value.
Adding Items: append, insert, and extend
To add a single item to the end, use append.
tasks = ["email Alex", "buy milk"]
tasks.append("study Python")
# ["email Alex", "buy milk", "study Python"]To add an item at a specific position, use insert. This shifts items to the right.
tasks = ["email Alex", "buy milk", "study Python"]
tasks.insert(1, "call bank")
# ["email Alex", "call bank", "buy milk", "study Python"]To add multiple items at once, use extend with another list.
tasks = ["email Alex"]
more_tasks = ["buy milk", "study Python"]
tasks.extend(more_tasks)
# ["email Alex", "buy milk", "study Python"]Beginner tip: append adds one item; extend adds each item from another list.
Removing Items: pop, remove, and del
There are several ways to remove items, and choosing the right one depends on what you know: the index or the value.
1) pop(index) removes and returns an item by index. If you omit the index, it removes the last item.
tasks = ["email Alex", "buy milk", "study Python"]
done = tasks.pop(0)
# done is "email Alex"
# tasks is ["buy milk", "study Python"]2) remove(value) removes the first matching value.
tasks = ["buy milk", "study Python", "buy milk"]
tasks.remove("buy milk")
# tasks is ["study Python", "buy milk"]3) del deletes by index (or a slice). It does not return the deleted item.
tasks = ["email Alex", "buy milk", "study Python"]
del tasks[1]
# ["email Alex", "study Python"]When you need the removed value (for logging, printing, or moving it elsewhere), pop is often the best choice.
Finding Data: in, index, and count
To check if a value exists in a list, use in.
tasks = ["email Alex", "buy milk"]
if "buy milk" in tasks:
print("Milk is on the list")To find the index of a value, use index. Be careful: it raises an error if the value is not found.
tasks = ["email Alex", "buy milk"]
position = tasks.index("buy milk") # 1To count occurrences, use count.
tasks = ["buy milk", "study Python", "buy milk"]
milk_times = tasks.count("buy milk") # 2Step-by-Step Mini Script: A Simple To-Do List Manager (List-Based)
This example shows storing and updating tasks using a list. It demonstrates adding, listing, and completing tasks.
Step 1: Start with an empty list
tasks = []Step 2: Add tasks with append
tasks.append("buy milk")
tasks.append("study Python")
tasks.append("email Alex")Step 3: Show tasks with their indexes
for i, task in enumerate(tasks):
print(i, "-", task)Step 4: Mark a task as done by removing it with pop
done_index = 1
finished = tasks.pop(done_index)
print("Finished:", finished)Step 5: Show remaining tasks
for i, task in enumerate(tasks):
print(i, "-", task)Key idea: the list is your storage, and methods like append and pop are your update tools.
Dictionaries: Storing Data by Name (Key) Instead of Position
Creating Dictionaries
You create a dictionary using curly braces {} with key: value pairs.
stock = {"apples": 10, "bananas": 5, "oranges": 8}Keys are often strings, and values can be any type (numbers, strings, lists, even other dictionaries).
Reading Values by Key
To get a value, use square brackets with the key.
stock = {"apples": 10, "bananas": 5}
apples_left = stock["apples"] # 10Important: if the key doesn’t exist, stock["pears"] raises an error. A safer option is get, which returns None (or a default value) if the key is missing.
stock = {"apples": 10}
pears_left = stock.get("pears") # None
pears_left = stock.get("pears", 0) # 0Updating Dictionaries: Changing an Existing Value
Assign to a key to update its value.
stock = {"apples": 10, "bananas": 5}
stock["bananas"] = 7
# {"apples": 10, "bananas": 7}This is similar to updating a list by index, but you update by key instead of position.
Adding New Key-Value Pairs
If the key doesn’t exist yet, assignment creates it.
stock = {"apples": 10}
stock["pears"] = 4
# {"apples": 10, "pears": 4}You can also add multiple pairs using update.
stock = {"apples": 10}
stock.update({"bananas": 5, "oranges": 8})Removing Key-Value Pairs: pop and del
pop removes a key and returns its value.
stock = {"apples": 10, "bananas": 5}
removed = stock.pop("bananas")
# removed is 5
# stock is {"apples": 10}del removes a key without returning the value.
stock = {"apples": 10, "bananas": 5}
del stock["bananas"]Use pop when you want the removed value for something (like printing what was removed).
Checking Keys: in and keys()
To check if a key exists, use in on the dictionary (it checks keys by default).
stock = {"apples": 10}
if "apples" in stock:
print("We have apples")You can also view keys, values, or both:
stock = {"apples": 10, "bananas": 5}
all_keys = stock.keys()
all_values = stock.values()
all_items = stock.items()These are “views” of the dictionary contents, often used in loops.
Step-by-Step Mini Script: Updating Inventory with a Dictionary
This example shows how dictionaries shine when you need to update quantities by name.
Step 1: Create starting inventory
inventory = {"apples": 10, "bananas": 5}Step 2: Receive a shipment (add to existing quantity)
inventory["apples"] = inventory["apples"] + 6
# apples becomes 16Step 3: Sell items (subtract), but avoid missing keys
item = "bananas"
sold = 2
if item in inventory:
inventory[item] = inventory[item] - soldStep 4: Handle a new product that wasn’t in the dictionary
new_item = "oranges"
received = 8
inventory[new_item] = inventory.get(new_item, 0) + receivedThis pattern is extremely common: dict.get(key, 0) + amount lets you update whether the key exists or not.
Step 5: Remove items that reach zero
for name in list(inventory.keys()):
if inventory[name] <= 0:
inventory.pop(name)Notice the list(inventory.keys()): it creates a separate list of keys so you can safely remove items while iterating.
Choosing Between a List and a Dictionary
Use a List When…
- You care about order (first, second, third).
- You want duplicates (two identical entries are allowed).
- You mainly process items in sequence.
Use a Dictionary When…
- You want to look up values by a label (key).
- You want fast access to a specific item by name.
- You want to store “properties” of something (like a profile).
A helpful mental model: a list is like a numbered checklist; a dictionary is like a labeled cabinet where each drawer has a name.
Common Patterns for Updating Stored Data
Pattern 1: Accumulating Totals in a Dictionary
Suppose you have a list of purchases and want totals per category. A dictionary is perfect for “grouping” and updating.
purchases = [
("food", 12.50),
("transport", 3.20),
("food", 7.10),
("books", 15.00)
]
totals = {}
for category, amount in purchases:
totals[category] = totals.get(category, 0) + amount
print(totals)
# {'food': 19.6, 'transport': 3.2, 'books': 15.0}The key update idea is: read the old value (or 0 if missing), then write back the new value.
Pattern 2: Keeping a List of Records (List of Dictionaries)
Sometimes you need multiple “records” that each have named fields. A common beginner-friendly structure is a list of dictionaries.
students = [
{"name": "Ava", "score": 88},
{"name": "Noah", "score": 92},
{"name": "Mia", "score": 75}
]To update a specific student’s score, you typically search and then update the dictionary.
target_name = "Mia"
new_score = 80
for student in students:
if student["name"] == target_name:
student["score"] = new_score
breakThis is a realistic example of “stored data” (the list) and “updating data” (changing a field in one dictionary).
Pattern 3: Building an Index (Dictionary that Points to List Positions)
If you frequently need to find items by name in a list, searching each time can become repetitive. One approach is to build a dictionary that maps a name to an index.
students = [
{"name": "Ava", "score": 88},
{"name": "Noah", "score": 92},
{"name": "Mia", "score": 75}
]
index_by_name = {}
for i, student in enumerate(students):
index_by_name[student["name"]] = i
mia_index = index_by_name["Mia"]
students[mia_index]["score"] = 80This shows how lists and dictionaries can work together: the list stores the records, the dictionary speeds up lookups.
Mutability: Why Updates “Stick”
Lists and dictionaries are mutable, which means you can change them after creating them. When you call append on a list or assign to a dictionary key, you are modifying the existing object.
This is powerful, but it also means you should be careful when two variables refer to the same list or dictionary.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]Here, a and b refer to the same list. If you want a separate copy, make one explicitly.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]Dictionaries have a similar copy() method.
Practical Script: A Small Contact Book (Dictionary + List)
This example stores contacts in a dictionary where each name maps to another dictionary of details. It demonstrates adding, updating, and deleting.
Step 1: Start with an empty contact book
contacts = {}Step 2: Add a contact
name = "Sam"
contacts[name] = {"phone": "555-0101", "email": "sam@example.com"}Step 3: Add another contact
name = "Rita"
contacts[name] = {"phone": "555-0202", "email": "rita@example.com"}Step 4: Update a field for an existing contact
contacts["Sam"]["phone"] = "555-9999"Step 5: Safely update only if the contact exists
target = "Alex"
if target in contacts:
contacts[target]["email"] = "alex@newmail.com"Step 6: Remove a contact and keep the removed data
removed_contact = contacts.pop("Rita")
print("Removed:", removed_contact)Step 7: List all contacts in a readable way
for name, info in contacts.items():
print(name, "-", info["phone"], "-", info["email"])Notice how the structure matches the problem: you want to find a contact by name (dictionary key), then update details (nested dictionary).
Common Beginner Mistakes (and How to Avoid Them)
Mistake 1: Using the Wrong Tool for Lookups
If you keep data in a list and repeatedly need to find an item by a label (like a product name), you may end up writing lots of search code. A dictionary can simplify this by making the label the key.
Mistake 2: Assuming Dictionary Order Is a “Sorting” Feature
Dictionaries preserve insertion order in modern Python, but that does not mean they are automatically sorted by key. If you need sorted output, you must sort the keys yourself.
stock = {"bananas": 5, "apples": 10, "oranges": 8}
for name in sorted(stock.keys()):
print(name, stock[name])Mistake 3: Modifying a Dictionary While Iterating Over It
Removing keys while looping directly over a dictionary can cause errors. If you need to remove items during iteration, loop over a separate list of keys.
inventory = {"apples": 0, "bananas": 3}
for name in list(inventory.keys()):
if inventory[name] == 0:
inventory.pop(name)Mistake 4: Confusing append with extend
If you append a list to another list, you get a nested list (a list inside a list). If you want to add each item, use extend.
a = [1, 2]
b = [3, 4]
a.append(b)
print(a) # [1, 2, [3, 4]]
a = [1, 2]
a.extend(b)
print(a) # [1, 2, 3, 4]