Python - Remove List Item
Removing List Item can be achieved using several built-in methods that provide flexibility in how you remove list items. In this article, we'll explore the different ways to remove list items in Python.
Removing Item by Value with remove()
The remove() method allows us to remove the first occurrence of a specific value from the list. If the item appears multiple times, only the first instance is removed. If the value is not found, Python raises a ValueError.
# List of countries
li = ['USA', 'Canada', 'Germany', 'France', 'Spain']
# Remove 'Germany' from the list
li.remove('Germany')
# Print the updated list
print(li)
Output
['USA', 'Canada', 'France', 'Spain']
Let's take a look at other cases of removing an item from a list:
Table of Content
Remove Element from List by Index
Below, are the methods of remove an element from a list by using the index value in Python.
- Using List Comprehension
- Using del keyword
- Using remove() Function
- Using pop() Function
Using List Comprehension
List comprehension provides a concise way to create a new list, excluding the element at a specific index.
# Initial list
a = [10, 20, 30, 40, 50]
# Index of the element to remove
idx = 2
# Removing element using list comprehension
a = [item for i, item in enumerate(a) if i != idx]
print(a)
Using del Keyword
The del keyword is used to delete an element at a specific index.
# Initial list
a = [10, 20, 30, 40, 50]
# Index of the element to remove
idx = 2
# Removing element using del
del a[idx]
print(a)
Using remove() Function
The remove() function removes the first occurrence of a specific value, but it requires the actual value, not the index. To use this with an index, you need to access the value at that index first.
# Initial list
a = [10, 20, 30, 40, 50]
# Index of the element to remove
idx = 2
# Removing element using remove() function
a.remove(a[idx])
print(a)
Using pop() Function
The pop() function removes and returns the element at the specified index. If no index is provided, it removes the last item.
# Initial list
a = [10, 20, 30, 40, 50]
# Index of the element to remove
idx = 2
# Removing element using pop() function
a.pop(idx)
print(a)
Removing All Items from List
If you want to remove all items from a list, you can use the clear() method or the del statement.
Using clear() Method:
# List of hobbies
a = [1, 2, 3, 4]
# Remove all items from the list
a.clear()
# Print the updated list
print(a)
Using del method:
# List of animals
a = ['Dog', 'Cat', 'Rabbit', 'Horse']
# Remove all items from the list
del a[:]
# Print the updated list
print(a)
In both examples, all items from the list were removed, leaving it empty.