What are the two methods for removing items from a list in Python?

In this python tutorial, we look at all the different methods you could use to remove item from list in python. We also break down which methods are best suited for each use case.

Table of Contents

  • Removing items from list python
  • Using Value to remove items
  • Remove item from list by Index
  • Remove item from list using del
  • Limitations and Caveats

Removing items from list - Python

Since lists are mutable, python comes built with a few list methods that can be used to remove items from lists. Some of these methods are pop(), remove(), clear(), etc.

Although all these methods can be used to remove items from lists in python they are built to cater to different use-cases, we discuss them in detail below.

Apart from these list methods, the del() method can also be used to remove items in a list.

Using Value to remove items

In this method, we remove items from the list based on their value. We achieve this by using the remove() list method. This method is quite straightforward, however, it is case sensitive and only removes the first occurrence of the value.

Passing the value in the wrong case would return a ValueError..

Syntax of remove():

list.remove(value) Here list refers to the name of the list.

Parameters:

value - The element that you want to remove.

Code to remove item from list by value:

list1 = ["Hire","Hire", "the", "top", 10, "python","freelancers"] list1.remove("Hire") print(list1) #Output - ['Hire', 'the', 'top', 10, 'python', 'freelancers']

As you can see, only the first occurrence of "Hire" was deleted. You could also try breaking the code trying to remove a lower case "hire".

Remove item from list by Index:

Since lists are ordered, each item can be referred to using its index. These indexes refer to a unique value and hence it can be used to remove items from a list in python.

For this, we use the pop() methods. Another use case of pop() is to remove and return the deleted item. In such cases pop() is used instead of remove(). Also, note that if no index is passed as a parameter, pop() removes and returns the last item.

Syntax of pop()

list.pop(index) Here list refers to the name of the list.

Parameters:

index - Optional, the index of the item you want to remove.

Returns:

Return the item removed from the list, in case you do not pass an index the last value is returned.

Code to remove item from list by index:

list1 = ["Hire", "the", "top", 10, "python","freelancers"] removed_item = list1.pop(0) print(list1) print(removed_item) #Output - ['the', 'top', 10, 'python', 'freelancers'] #Output - "Hire"

Remove item from list using del:

del is another way to remove items from a list in python. Although this is not a list method it does come with a unique use case.

Similar to pop(), del also removes items using their index. However, what’s unique is that it can be used to remove multiple items at a time.

Syntax of del:

del object_name

Passing the name of the list followed by the index or an index range after del will remove the items from the list in python.

Code to remove items using del

list1 = ["Hire", "the", "top", 10, "python","freelancers"] del list1[0] print(list1) #Output - "['the', 'top', 10, 'python', 'freelancers']"

And if you are looking to remove multiple items from a list, adding an index range would help you achieve this.

list1 = ["Hire", "the", "top", 10, "python","freelancers"] del list1[0:4] print(list1) #Output - ['python', 'freelancers']

Limitations and Caveats:

  • While trying to remove items from a list in python using remove(), a ValueError is returned if the parameter cannot be found
  • The pop() only allows int values to be passed as a parameter, and an IndexError is returned if the index is out of range

Python Lists have various in-built methods to remove items from the list. Apart from these, we can also use different methods to remove an element from the list by specifying a position using Python.

Delete an element from a list using the del 

The Python del statement is not a function of List. Items of the list can be deleted using the del statement by specifying the index of the item (element) to be deleted. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

del lst[1]

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

In this method, we are using list comprehension. Here, we are appending all the elements except the elements that have to be removed.

list1 = [1, 9, 8, 4, 9, 2, 9]

print ("original list : "+ str(list1))

list1 = [ele for ele in list1 if ele != 9]

print ("List after element removal is : " + str(list1))

Outputoriginal list : [1, 9, 8, 4, 9, 2, 9] List after element removal is : [1, 8, 4, 2]

We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst.remove('Orchids')

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

Delete an element from a List using pop() 

The pop() is also a method of listing. We can remove the element at the specified index and get the value of that element using pop(). 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

a = lst.pop(1)

print("Item popped :", a)

print("After deleting the item :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] Item popped : Orchids After deleting the item : ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations']

Remove an item from a list using discard() method

In this method, we convert a list into a set and then delete an item using the discard() function. Then we convert the set back to the list.

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst = set(lst)

lst.discard('Orchids')

lst=list(lst)

print("List after element removal is :", lst)

OutputOriginal List is : ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations'] List after element removal is : ['Lily', 'Carnations', 'Iris', 'Rose', 'Lavender']

Note: Since the list is converted to a set, all duplicates will be removed and the ordering of the list cannot be preserved.

Remove an item from a list using filter() method

In this method, we filter the unwanted element from the list using the filter() function. 

lst = ['Iris', 'Orchids', 'Rose', 'Lavender',

    'Lily', 'Carnations']

print("Original List is :", lst)

lst1 = filter(lambda item: item!='Orchids',lst)

print("List after element removal is :", list(lst1))

Output('Original List is :', ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']) ('List after element removal is :', ['Iris', 'Rose', 'Lavender', 'Lily', 'Carnations'])


Última postagem

Tag