Python List remove(x) MethodPython remove() method removes the first item from the list which is equal to the passed value. It throws an error if the item is not present in the list. The method adjusts the original list set up and brings None back. In the event that the predefined element isn't found in the list, a ValueError is raised. Signature and examples are described below. Syntax:Parametersx : Element to be deleted. ReturnIt does not return any value rather modifies the list. Let's see some examples of remove() method to understand it's functionality. Python List remove() Method Examples:Let's see some examples of remove() method to understand it's functionality. Example 1: Eliminating a particular element from a listA simple example in which we are removing an element from the list. Code Output: 1 2 3 After removing: 1 3 Example 2: Removing duplicate element from the listIf list contains duplicate elements, the method will remove only first occurred element. See the example below. Code Output: 1 2 3 2 After removing: 1 3 2 Example 3: Dealing with a ValueError when an element isn't in the listIf we remove an element which is not found in the list, it throws an error to the console. See the example below. Code Output: 1 2 3 2 ERROR! Traceback ( most recent call last ): File " < string > ", line 6, in < module > ValueError : list.remove(x) : x not in list Example 4: Eliminating an element by indexWe make a list of numbers and call the pop() method on the list, passing in the index of the element we need to eliminate. This eliminates the element at the index from the list. Code Output: Original list is : [' 1 ', ' 2 ', ' 3 ', ' 4 '] Element at the index 2 is removed The Modified list is : [' 1 ', ' 2 ', ' 4 '] Example 5: Eliminating all occurrences of an element from a listWe create a list of numbers that contains different occurrences of the number. We then utilize some time circle to repeatedly call the eliminate() method on the list until all occurrences of the number have been taken out. Code Output: Original list is : [1, 2, 2, 3, 4, 5, 3, 9, 3] The Modified list is : [1, 2, 2, 4, 5, 9] Conclusion:The remove() method in Python is a valuable device for eliminating elements from a list. Additionally, you can utilize the remove() method related to loops, list comprehensions, and filter functions to remove different elements from a list based on conditions.
Next TopicPython Lists
|