How to remove an element from a list in Python
In this article, we will go through the methods for removing an element from a list. We will discuss remove()
and pop()
methods.
Method 1: remove()
To remove an element from a list, you can use the built-in list function remove().
- The remove() method removes the first matching element (which is passed as an argument) from the list.
- Syntax:
listname.remove(element)
- The remove() method takes a single element as an argument and removes it from the list.
- If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception
- The remove() doesn’t return any value.
Example:
#initial list colors = ['red', 'green', 'blue', 'yellow', 'white'] print("Initial list ", colors) #removing the element 'yellow' colors.remove('yellow') print ("List after removal: ", colors)
Output:
Initial list ['red', 'green', 'blue', 'yellow', 'white'] List after removal: ['red', 'green', 'blue', 'white']
Method 2: pop()
- The pop() method removes the item at the given index from the list and returns the removed item
- Syntax:
listname.pop(index)
- The
pop()
method takes a single argument. This argument is optional. If the index is given, then this function will pop out the last item on the list. [The default value is set to -1]
- If the index is out of range, it throws IndexError: pop index out of range exception.
Example:
#initial list colors = ['red', 'green', 'blue', 'yellow', 'white'] print("Initial list ", colors) #removing the element 'yellow' print ("Removed element is ", colors.pop(2)) print ("List after removal: ", colors)
Output:
Initial list ['red', 'green', 'blue', 'yellow', 'white'] Removed element is blue List after removal: ['red', 'green', 'yellow', 'white']
Subscribe
Login
Please login to comment
0 Discussion