How to Delete an Element from a List in Python

In Python, there are several methods available that allow the user to remove elements from a list.
remove()
The remove()
method will remove the first instance of a value in a list.
list = [1, 2, 3, 1] #remove the first instance of the value list.remove(1)
Output:
[2, 3, 1]
pop()
The pop()
method removes an element at a given index, and will return the removed item.
numbers = [10, 20, 30, 40] ten = numbers.pop(0) print(numbers) print(ten)
Output:
[20, 30, 40] 10
del
The del
keyword in Python is also used to remove an element or slice from a list.
numbers = [1,2,3,4,5,6,7,8,9] del numbers[3:6] print(numbers)
Output:
[1, 2, 3, 7, 8, 9]
Subscribe
Login
Please login to comment
0 Discussion