Deleting List Items in Python
Deleting List Items in Python
The list class methods remove() and pop() both remove items from a list. The difference between them is that the remove() method removes the object given an argument, while the pop() method removes the item at a given index.
Using the remove() Method
The following example shows how to use the remove() method to remove list items –
list1 = ["Rohan", "Physics", 21, 69.75]
print ("Original list: ", list1)
list1.remove("Physics")
print ("List after removing: ", list1)
It will produce the following output –
Original list: ['Rohan', 'Physics', 21, 69.75]
List after removing: ['Rohan', 21, 69.75]
Using the pop() method
The following example shows how to use the pop() method to delete a list item.
list2 = [25.50, True, -55, 1+2j]
print ("Original list: ", list2)
list2.pop(2)
print ("List after popping: ", list2)
It will produce the following output −
Original list: [25.5, True, -55, (1+2j)]
List after popping: [25.5, True, (1+2j)]
Using the “del” keyword
Python has a “del” keyword that can delete any Python object from memory.
Example
We can use “del” to delete an item from a list. See the following example:
list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
del list1[2]
print ("List after deleting: ", list1)
It will produce the following output: Output –
Original list: ['a', 'b', 'c', 'd']
List after deleting: ['a', 'b', 'd']
Example
You can use the slice operator to delete a range of consecutive items from a list. Please see the following example –
list2 = [25.50, True, -55, 1+2j]
print ("List before deleting: ", list2)
del list2[0:2]
print ("List after deleting: ", list2)
This will produce the following output –
List before deleting: [25.5, True, -55, (1+2j)]
List after deleting: [-55, (1+2j)]