Lists — Mutation Methods
Modify lists with append, insert, remove, and more. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Append and ExtendStudy Material
Read the full lesson
Lists are mutable
In Python, strings are "immutable", meaning once you create "Python", you cannot change the 'P' to a 'C'. You have to create a brand new string.
Lists, however, are mutable. You can easily add, remove, and change items inside a list after it has been created.
Changing an existing item
To change an item, you access it via its index and simply assign a new value to it with =.
pythoninventory = ["Sword", "Shield", "Potion"] # Swap the Shield for a Bow inventory[1] = "Bow" print(inventory) # Output: ['Sword', 'Bow', 'Potion']
Adding items
.append()
The most common way to add an item is to slap it onto the very end of the list using the .append() method.
pythonshopping_cart = ["Milk", "Eggs"] shopping_cart.append("Bread") print(shopping_cart) # Output: ['Milk', 'Eggs', 'Bread']
.insert()
If you need to put an item in a specific spot, use .insert(). You provide the index, then the item.
python# Insert "Apples" at index 1 shopping_cart.insert(1, "Apples") print(shopping_cart) # Output: ['Milk', 'Apples', 'Eggs', 'Bread']
Removing items
.remove()
If you know the value of the item you want to remove, use .remove(). Python scans the list from left to right and deletes the first match it finds.
pythoncolors = ["Red", "Green", "Blue", "Green"] colors.remove("Green") print(colors) # Output: ['Red', 'Blue', 'Green'] (Notice only the first 'Green' was removed!)
If the item isn't in the list, Python will throw a ValueError.
.pop()
If you know the index of the item, use .pop(). It deletes the item at that spot.
If you leave the parentheses empty (), .pop() automatically removes and returns the very last item in the list.
pythondeck = ["Ace", "King", "Queen"] # Remove and grab the last item drawn_card = deck.pop() print(f"You drew the {drawn_card}!") print(f"Remaining deck: {deck}")
What this lesson should give you
After this lesson, you should understand how to:
- overwrite an existing item using its index (
my_list[0] = "New") - add an item to the end of a list using
.append() - add an item at a specific location using
.insert() - delete an item by its value using
.remove() - delete an item by its index, or grab the last item, using
.pop()
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Append and Extend
Complete the "Append and Extend" exercise.
Insert at Position
Complete the "Insert at Position" exercise.
Remove by Value
Complete the "Remove by Value" exercise.
Pop Last Item
Complete the "Pop Last Item" exercise.
Clear All Items
Complete the "Clear All Items" exercise.