- Use the
delkeyword to remove an item from a list by its index. - Use the
.remove()method to remove an item from a list by its value. - Explain the difference between the two removal techniques.
Removing Items from a List
As you build your programs, you'll often need to remove items from a list. Python gives you two primary tools for this, and they are used in different situations.
Method 1: Removing by Position with del
If you know the index of the item you want to remove, you use the del keyword. This permanently deletes the item at that position, and the list shrinks to fill the gap.
tasks = ["laundry", "dishes", "homework"]
# Let's remove the item at index 1 ("dishes")
del tasks[1]
print(tasks) # Output: ['laundry', 'homework']
Method 2: Removing by Value with .remove()
If you know the value of the item you want to remove but not its index, you use the .remove() list method. Python will search the list for the first matching item and remove it.
tasks = ["laundry", "dishes", "homework"]
# Let's remove the item with the value "laundry"
tasks.remove("laundry")
print(tasks) # Output: ['dishes', 'homework']
Knowledge Check: Choose Your Tool
Let's see if you can remember which tool to use in which situation. Complete the interactive exercise below.
Live Example: Managing a To-Do List
The Trinket below demonstrates both removal methods. Run it, then follow the "Your Turn" instructions to practice removing items yourself.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.