API Navigator Logo

Removing Items from a Python List

Author: Newtum

This guide covers the primary methods for removing elements from a list in Python: `remove()`, `pop()`, and the `del` statement.

Using `list.remove()` to Remove by Value

The `.remove()` method searches for the first occurrence of a specified value and removes it from the list. It raises a `ValueError` if the item is not found.

fruits = ['apple', 'banana', 'cherry', 'banana']
print(f"Original list: {fruits}")

# Remove the first 'banana'
fruits.remove('banana')
print(f"After removing 'banana': {fruits}")

try:
    fruits.remove('orange')
except ValueError:
    print("'orange' was not found in the list.")

Using `list.pop()` to Remove by Index

The `.pop()` method removes an item at a specific index and returns it. If no index is specified, it removes and returns the last item in the list.

numbers = [10, 20, 30, 40, 50]
print(f"Original list: {numbers}")

# Remove and get the item at index 2
removed_item = numbers.pop(2)
print(f"Removed item: {removed_item}")
print(f"List after pop(2): {numbers}")

# Remove and get the last item
last_item = numbers.pop()
print(f"Last item removed: {last_item}")
print(f"List after pop(): {numbers}")

Using the `del` Statement

The `del` statement can remove an item at a specific index or remove a slice of items. It doesn't return any value.

letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(f"Original list: {letters}")

# Delete the item at index 0
del letters[0]
print(f"After del letters[0]: {letters}")

# Delete a slice of items (from index 1 to 3)
del letters[1:4]
print(f"After del letters[1:4]: {letters}")