How to remove an item from a list in python

How to remove an item from a python list :

In this tutorial, we will learn how to remove an item from a list in python. We will learn how to remove an element using its value from a list and how to remove using an index. Also, we will learn how to remove all elements from a list.
Python provides different methods for list deleting operation. Let’s take a look at them one by one :

Removing item using list.remove(x) :

remove() method is defined as :

list.remove(x)

It will remove the first element of the provided list with a value equal to x. e.g. :

givenList = ['a','b','c','d','e','f']
print(givenList)

givenList.remove('c')
print(givenList)

It will remove the ‘c’ from the list. If the value is not found, it will raise ValueError.
python remove item from list

Removing item using list.pop(i) :

Another method of removing an element from a list is pop. This method takes the index of the element to remove as the parameter. It returns that indexed element from the list. This value is optional. If we don’t pass it, it will return the last element of the list.

givenList = ['a','b','c','d','e','f']
print(givenList)

print(givenList.pop(2))
print(givenList.pop())

The first print will print out c and the second one will print out f as the output.
python remove list item

Removing all elements from a list :

To remove all elements of a list, we can use clear() method. For example :

givenList = ['a','b','c','d','e','f']
print(givenList)

givenList.clear()
print(givenList)

It will print one empty list [] as the output.
python remove list item

Removing elements using del :

del is a powerful statement for removing list values in python. Using it, we can remove an element using a specific index. pop method also takes one index and remove the element at this index. The only difference is that pop returns a value and del doesn’t return a value.
Using del, we can either remove one specific value, remove slice from a list or clear the entire list.

givenList = ['a','b','c','d','e','f']
print(givenList)

del givenList[3]
print(givenList)

del givenList[2:4]
print(givenList)

del givenList[:]
print(givenList)

It will print :

['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'e', 'f']
['a', 'b', 'f']
[]

python remove list item
You might also like :

Leave a Reply