in this post, I am going to let you know different ways to remove an item from a list in python. We can use clear, pop, remove, and del methods to remove an element from a list.
Python has a number of in-built methods that help to remove an item from a list. I will describe one by one method with examples to remove elements.
The list has clear()
, pop()
, and remove()
method to remove an item.
Python Remove an Element From a List
We will learn about the Python List remove an item methods with the help of examples.
We’ll cover the following functionality in this tutorial:
- The
clear()
method is help to remove all items from a list. - The
pop()
helps to remove an item by index and get its value. - The
remove()
method helps to remove an item by value. - The
del
remove items by index or slice:
clear()
This method is used to remove all items from a list.
items = list(range(5)) print(items) items.clear() print(items)
Output :
[0, 1, 2, 3, 4] []
pop() Method
The pop()
method is used to remove the item at the specified position and get its value. The starting index is zero. You can also use negative values to specify the position from the end.
items = list(range(5)) print(items) print(items.pop(0)) print(items.pop(3)) print(items.pop(-2))
Output :
[0, 1, 2, 3, 4] 0 4 2
remove() Method
The remove() method removes the first matching element which is passed as an argument to the method from the list.
items = list(range(5)) print(items) items.remove(4) print(items)
Output :
[0, 1, 2, 3, 4] [0, 1, 2, 3]
Remove Element Using del
The del method removes the element by index or slice. The first index is 0, and the last index is -1.
items = list(range(5)) print(items) del items[1] print(items)
Output :
[0, 1, 2, 3, 4] [0, 2, 3, 4]