Question
How to remove an element from a list?
Solution
β Verified
You can remove elements from a list in Python using several methods, depending on how you want to remove them.
1. remove(value)
- Removes the first occurrence of a specific value.
- Raises an error if the value is not found.
a = [1, 2, 3, 2] a.remove(2) print(a) # Output: [1, 3, 2]
2. pop(index)
- Removes and returns the element at the specified index.
- If no index is given, removes the last item.
- Raises an error if the index is out of range.
a = [10, 20, 30] a.pop(1) print(a) # Output: [10, 30]
3. del statement
- Deletes an element by index, or slices of the list.
a = [5, 6, 7, 8] # Delete element by index del a[2] print(a) # Output: [5, 6, 8] # Delete a slice del a[1:3]
Click here to download practice questions on
Python Lists