How to Remove Item from a List in Python (original) (raw)
Last Updated : 20 Nov, 2024
Lists in Python have various built-in methods to remove items such as **remove, pop, del and **clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the **element or **index.
The simplest way to remove an element from a list by its **value is by using the remove()method. Here’s an example:
Python `
a = [10, 20, 30, 40, 50] a.remove(30) print(a)
`
Let’s us see different method to remove elements from the list.
Table of Content
- Using remove() to removing by value
- Using pop() to Remove by Index
- Using del() to remove by index
- Using Clear() to remove all elements
Using remove() – remove item by value
The**remove() method **deletes the first occurrence of a specified value in the list. If multiple items have the same value, only the first match is removed.
Python `
a = [10, 20, 30, 20, 40, 50]
Remove the first occurance of 20
a.remove(20) print(a)
`
Output
[10, 30, 20, 40, 50]
Using pop() – remove item by Index
The pop() method can be used to remove an element from a list based on its **index and it also returns the removed element. This method is helpful when we need to both **remove and **access the item at a specific position.
Python `
a = [10, 20, 30, 40, 50]
Remove element at index 1 and return its value in val
val = a.pop(1) print(a) print("Removed Item:", val)
`
Output
[10, 30, 40, 50] Removed Item: 20
If we do not specify the index then **pop() method removes the last element.
Python `
a = [10, 20, 30, 40, 50]
This will remove the last element
val = a.pop() print(a) print("Removed Item:", val)
`
Output
[10, 20, 30, 40] Removed Item: 50
Using del() – remove item by index
The del statement can remove elements from a list by specifying their index or a range of indices.
Removing a single element by index
Python `
a = [10, 20, 30, 40, 50]
Removes element at index 2 (which is 30).
del a[2] print(a)
`
Removing multiple elements by index range
We can also use **del to remove multiple elements from a list by specifying a range of indices.
Python `
a = [10, 20, 30, 40, 50, 60, 70]
Removes elements from index 1 to index 3 (which are 20, 30, 40)
del a[1:4] print(a)
`
Using clear() – remove all elements
If we want to remove all elements from a list then we can use the **clear() method. This is useful when we want to empty a list entirely but keep the list object.
Python `
a = [10, 20, 30, 40]
Empty a list entirely
a.clear() print(a)
`
Remove List Items in Python – Which method to use?
Method | Removes By | Returns Removed Element | Modifies List In-Place |
---|---|---|---|
remove() | Remove item by Value | No | Yes |
pop() | Remove item by Index (or last item) | Yes | Yes |
del | Remove by Index or range | No | Yes |
clear() | Remove all elements | No | Yes |
**Related Articles: