Removing Items from a List in python
Python provides several methods to remove items from a list. You can remove items by value, by index, remove all items, or even delete the entire list.
In this tutorial, you'll learn how to use remove(), pop(), del, and clear() with practical examples.
Using remove()
The method removes the first occurrence of the specified value from the list.
remove()
Syntax
list_name.remove(value)
Example
fruits = ["Apple", "Banana", "Mango"]
fruits.remove("Apple")
print(fruits)
Output:
['Banana', 'Mango']
The item "Apple" is removed from the list.
Using pop()
The method removes and returns an item at the specified index. If no index is provided, it removes the last item.
pop()
Syntax
list_name.pop(index)
# Or
list_name.pop()
Example: Remove Last Item
fruits = ["Apple", "Banana", "Mango"]
fruits.pop()
print(fruits)
Output:
['Apple', 'Banana']
Example: Remove Item at a Specific Index
fruits = ["Apple", "Banana", "Mango"]
fruits.pop(1)
print(fruits)
Output:
['Apple', 'Mango']
Using del
The keyword removes an item at a specific index or deletes the entire list.
del
Example: Delete an Item
fruits = ["Apple", "Banana", "Mango"]
del fruits[1]
print(fruits)
Output:
['Apple', 'Mango']
Example: Delete the Entire List
fruits = ["Apple", "Banana", "Mango"]
del fruits
After deleting the list, trying to access it will raise an error because it no longer exists.
Using clear()
The method removes all items from a list but keeps the list itself.
clear()
Syntax
list_name.clear()
Example
fruits = ["Apple", "Banana", "Mango"]
fruits.clear()
print(fruits)
Output:
[]
The list still exists, but it contains no items.
Difference Between clear() and del
| Method | Result |
|---|---|
clear()
|
Removes all items but keeps the list |
del list_name
|
Deletes the entire list |
Summary
| Method | Description |
|---|---|
remove()
|
Removes an item by value |
pop()
|
Removes an item by index (default: last item) |
del
|
Deletes an item or the entire list |
clear()
|
Removes all items from the list |