Unit 4 · Lesson 2

Modifying Lists

Lists are mutable — you can add, remove, and rearrange items after creation.

Add items with append() and insert()
Remove items with remove() and pop()
Check membership with the in keyword
Reassign items by index

Lists Are Mutable

Unlike strings, you can change lists after creating them. Python gives you several methods:

fruits = ["apple", "banana"] fruits.append("cherry") # Add to end → ["apple", "banana", "cherry"] fruits.insert(1, "blueberry") # Insert at index 1 fruits.remove("banana") # Remove first occurrence last = fruits.pop() # Remove & return last item fruits[0] = "avocado" # Replace by index

Checking Membership

Use in to check if an item exists in a list:

if "apple" in fruits: print("Found it!")
Key distinction: append() adds to the end, insert(i, item) adds at position i, remove(item) removes by value, pop() removes by position (default: last).
Practice Time

Challenges

🛒

Challenge 1: Shopping List

Guided

Build a shopping list, then remove items as you buy them.

Instructions: Start with shopping list. Append "eggs" and "bread". Remove "milk". The final list should have the correct items.
Hint: shopping.append("eggs"), shopping.append("bread"), shopping.remove("milk")
🚶

Challenge 2: Queue Simulator

Guided

Simulate a queue: people join at the back and leave from the front.

Instructions: Start with queue. Add "Diana" to the back. Then remove the first person and store them in served.
Hint 1: queue.append("Diana")
Hint 2: served = queue.pop(0) removes and returns the first item
🎒

Challenge 3: Inventory Manager

Solo

Manage a game inventory: add, check, and remove items.

Instructions: Start with inventory. Add "shield". Check if "sword" is in inventory — store True/False in has_sword. Remove "potion". Store the final inventory length in item_count.
Hint: has_sword = "sword" in inventory, item_count = len(inventory)

Challenge 4: Unique Only

Stretch

Build a new list containing only unique values from the original.

Instructions: Given numbers with duplicates, build a unique list containing each value only once (in order of first appearance). Use a loop and the in keyword.
Hint: for n in numbers: then if n not in unique: unique.append(n)