Python list remove element by value

Python: Remove elements from list by value

This article will discuss different ways to remove first or all occurrences of an element from a list by value.

Table of Contents

Python: Remove the first occurrence of an element from a list by value

In Python, the list class provides a function remove(value) to delete an element from the list. It accepts a value as an argument and deletes the first occurrence of that value from the list. But if the given value does not exist in the list, then it raises the ValueError.

Now let’s use the remove() function to delete the first occurrence of an element 52 from a list of numbers,

list_of_num = [51, 52, 53, 54, 55, 52, 57, 52, 59] # Remove first occurrence of 52 from list list_of_num.remove(52) print(list_of_num)

Frequently Asked:

The list had multiple occurrences of 52, but the remove() function deleted the first occurrence only.

Python: Remove element from a list by value if exist

What if we call the remove() function to delete an element that does not exist in a list? In that case, it will give Value Error. For example,

list_of_num = [51, 52, 53, 54, 55, 52, 57, 52, 59] list_of_num.remove(70)
list_of_num.remove(70) ValueError: list.remove(x): x not in list

We are trying to delete an element with value 72 from the list, but the list didn’t have that. Therefore it raised the value error. We should first check if the element exists in the list or not before calling the remove() function. For example,

list_of_num = [51, 52, 53, 54, 55, 52, 57, 52, 59] elem = 70 if elem in list_of_num: list_of_num.remove(elem) print(list_of_num)
[51, 52, 53, 54, 55, 52, 57, 52, 59]

Python: Remove all occurrences of an element from a list by value

As we saw in the previous examples, the remove() function always deletes the given element’s first occurrence from the list. To delete all the occurrences of an element, we need to call the remove() function in a loop, until all the occurrences are not deleted. For example,

def remove_all_occurrences(list_obj, value): while value in list_obj: list_of_num.remove(value) list_of_num = [51, 52, 52, 55, 55, 52, 57, 52, 55] remove_all_occurrences(list_of_num, 52) print(list_of_num)

It deleted all the occurrences of 52 from the list of numbers.

Python: Remove all occurrences of multiple elements from a list by values

In the previous example, we deleted all the occurrences of an element from the list. So we can use the same logic to delete all occurrences of multiple elements from the list.

Читайте также:  Python get last updated file

Suppose we have a list of numbers, and we have another list of values that we want to delete for the original list. We want to delete all elements of list2 from list1.

We have created a separate function for the same, it accepts two different lists as arguments,

  • The first one is the list from which we need to delete the elements
  • The second list contains the elements which we want to delete.

For each element of the second list, it deletes all the occurrences from the original list. Let’s understand by an example,

def remove_all_by_values(list_obj, values): for value in values: while value in list_obj: list_of_num.remove(value) list_of_num = [51, 52, 52, 55, 55, 52, 57, 52, 55, 61, 62] remove_all_by_values(list_of_num, [52, 55, 57]) print(list_of_num)

It deleted all the occurrences of 52, 55, and 57 from the list.

Summary

In this article, we learn different ways to delete the first or all occurrences of an element from a list. We also analyzed how to delete multiple elements from a list by value.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Читайте также:  Javascript что это пример

Источник

Python : How to remove element from a list by value or Index | remove() vs pop() vs del

In this article we will discuss different ways to remove an elements from list.

Remove an element from List by value using list.remove()

Python’s list provides a member function to remove an element from list i.e.

It removes the first occurrence of given element from the list.

Frequently Asked:

# List of numbers listOfnum = [12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56]

Let’s remove 56 from the given list using list.remove() i.e.

# Remove first occurrence of 56 from List listOfnum.remove(56)

It will remove the first occurrence of 56 from the above lists. Lists contents will be now,

[12, 44, 45, 34, 3, 56, 4, 33, 44, 56]

If we try to remove the element that doesn’t exists in list then list.remove() will throw exception.
Therefore before calling list.remove() we should either,

Check if element exists in list i.e.

# Check if element exist in List, before removing if 99 in listOfnum: listOfnum.remove(99) else: print("Given Element Not Found in List")
# If given element doesn't exists in list, then remove() can throw Error # Therefore use try / except while calling list.remove() try : listOfnum.remove(99) except ValueError: print("Given Element Not Found in List")

Related Articles

Remove an element from List by Index using list.pop()

In python list‘s pop() function will remove the element at given index and also returns the deleted element.
If index is not given then it deletes the last element.

We have a list of ints i.e.

# List of numbers listOfnum = [12, 44, 12, 56, 45, 34, 3, 56, 4, 33, 44, 56]

Let’s remove element at index 2

# Remove the element at index 2 in list value = listOfnum.pop(2)

List’s contents will be now

[12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56]

Returned value is 12 i.e. the deleted element.

list.pop() and Runtime Error

If list.pop() is called an index that is out of the boundary of List then it will generate a runtime error.
Therefore we should always check the size of list before calling list.pop() i.e.

# pop() can throw error if given index is out of range, so check size before calling it if len(listOfnum) >= 20: listOfnum.pop(20) else: print("Index Out of Range")
# pop() can throw error if given index is out of range, so use try / except try : listOfnum.pop(20) except IndexError: print("Index Out of Range")

Remove an element from List by del

In python del is a keyword and can be used to delete the element in list by index i.e.

It will delete the element at index 2 in list.

If del list[index] is called on an index that is out of the boundary of List then it will generate a runtime error.
Therefore check size of list before calling del i.e.

# del list[index] can throw error if given index is out of range, so check size before calling it if len(listOfnum) >= 20: del listOfnum[20] else: print("Index Out of Range")
# del list[index] can throw error if given index is out of range, so use try / except try : del listOfnum[20] except IndexError: print("Index Out of Range")

Complete example is as follows,

def main(): # List of numbers listOfnum = [12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56] ''' Remove an element from List by value using list.remove() ''' print("*****list.remove()*****") print("Original List : " , listOfnum) # Remove first occurrence of 56 from List listOfnum.remove(56) print("Modified List : " , listOfnum) # If given element doesn't exists in list, then remove() can throw Error # Therefore use try / except while calling list.remove() try : listOfnum.remove(99) except ValueError: print("Given Element Not Found in List") # Check if element exist in List, before removing if 99 in listOfnum: listOfnum.remove(99) else: print("Given Element Not Found in List") ''' Remove an element from List by Index using list.pop() ''' print("*****list.pop()*****") # List of numbers listOfnum = [12, 44, 12, 56, 45, 34, 3, 56, 4, 33, 44, 56] print("Original List : ", listOfnum) # Remove the element at index 2 in list value = listOfnum.pop(2) print("Deleted Element : ", value) print("Modified List : ", listOfnum) # Remove the last element from list value = listOfnum.pop() print("Deleted Element : ", value) print("Modified List : ", listOfnum) # pop() can throw error if given index is out of range, so check size before calling it if len(listOfnum) >= 20: listOfnum.pop(20) else: print("Index Out of Range") # pop() can throw error if given index is out of range, so use try / except try : listOfnum.pop(20) except IndexError: print("Index Out of Range") print("*****del list[index]*****") ''' Remove an element from List by del ''' listOfnum = [12, 44, 56, 45, 34, 3, 4, 33, 44] print("Original List : ", listOfnum) # Delete element at index 2 del listOfnum[2] print("Modified List : ", listOfnum) # del list[index] can throw error if given index is out of range, so check size before calling it if len(listOfnum) >= 20: del listOfnum[20] else: print("Index Out of Range") # del list[index] can throw error if given index is out of range, so use try / except try : del listOfnum[20] except IndexError: print("Index Out of Range") if __name__ == '__main__': main()
*****list.remove()***** Original List : [12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56] Modified List : [12, 44, 45, 34, 3, 56, 4, 33, 44, 56] Given Element Not Found in List Given Element Not Found in List *****list.pop()***** Original List : [12, 44, 12, 56, 45, 34, 3, 56, 4, 33, 44, 56] Deleted Element : 12 Modified List : [12, 44, 56, 45, 34, 3, 56, 4, 33, 44, 56] Deleted Element : 56 Modified List : [12, 44, 56, 45, 34, 3, 56, 4, 33, 44] Index Out of Range Index Out of Range *****del list[index]***** Original List : [12, 44, 56, 45, 34, 3, 4, 33, 44] Modified List : [12, 44, 45, 34, 3, 4, 33, 44] Index Out of Range Index Out of Range

Источник

Оцените статью