Introduction to Computer Science/5.4 Removing Items from a List

5.4 Removing Items from a List

🎯 Learning Goals for This Page
  • Use the del keyword 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.

Note

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.

Python 3Initializing...
Loading code editor...
Program output will appear here...

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...