How to remove an element from a list in Python
Python provides the following methods to remove one or multiple elements. We can delete the elements using the del keyword by specifying the index position. Let’s understand the following methods.
- remove()
- pop()
- clear()
- del
- List Comprehension – If specified condition is matched.
The remove() method
The remove() method is used to remove the specified value from the list. It accepts the item value as an argument. Let’s understand the following example.
Example –
Output:
The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Bob', 'Charlie', 'Bob', 'Dave']
If the list contains more than one item of the same name, it removes that item’s first occurrence.
Example –
Output:
The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Charlie', 'Bob', 'Dave']
The pop() method
The pop() method removes the item at the specified index position. If we have not specified the index position, then it removes the last item from the list. Let’s understand the following example.
Example –
Output:
The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie']
We can also specify the negative index position. The index -1 represents the last item of the list.
Example –
Output:
The list is: ['Joseph', 'Bob', 'Charlie', 'Bob', 'Dave'] After removing element: ['Joseph', 'Bob', 'Charlie', 'Dave']
The clear() method
The clear() method removes all items from the list. It returns the empty list. Let’s understand the following example.
Example –
Output:
[10, 20, 30, 40, 50, 60] []
The del statement
We can remove the list item using the del keyword. It deletes the specified index item. Let’s understand the following example.
Example –
Output:
[10, 20, 30, 40, 50, 60] [10, 20, 30, 40, 50] [10, 20, 30, 40]
It can delete the entire list.
Output:
Traceback (most recent call last): File "C:/Users/DEVANSH SHARMA/PycharmProjects/Practice Python/first.py", line 14, in print(list1) NameError: name 'list1' is not defined
We can also delete the multiple items from the list using the del with the slice operator. Let’s understand the following example.
Example –
Output:
[10, 20, 30, 40, 50, 60] [10, 40, 50, 60] [60] []
Using List Comprehension
The list comprehension is slightly different way to remove the item from the list. It removes those items which satisfy the given condition. For example – To remove the even number from the given list, we define the condition as i % 2 which will give the reminder 2 and it will remove those items that’s reminder is 2.
Let’s understand the following example.
Example –
Output:
[20, 34, 40, 60] [11, 45]