Table of Contents
ToggleRemoving list items in Python implies deleting elements from an existing list. Lists are ordered collections of items, and sometimes you need to remove certain elements from them based on specific criteria or indices. When we remove list items, we are reducing the size of the list or eliminating specific elements.
We can remove list items in Python using various methods such as remove(), pop(), and clear(). Additionally, we can use the del statement to remove items at a specific index. Let us explore through all these methods in this tutorial.
remove() MethodThe remove() method in Python is used to remove the first occurrence of a specified item from a list.
We can remove list items using the remove() method by specifying the value we want to remove within the parentheses, like my_list.remove(value), which deletes the first occurrence of value from my_list.
list1 = ["Rohan", "Physics", 21, 69.75]
print("Original list:", list1)
list1.remove("Physics")
print("List after removing:", list1)
Output:
Original list: ['Rohan', 'Physics', 21, 69.75]
List after removing: ['Rohan', 21, 69.75]
pop() MethodThe pop() method in Python is used to remove and return the last element from a list if no index is specified, or remove and return the element at a specified index, altering the original list.
We can remove list items using the pop() method by calling it without any arguments my_list.pop(), which removes and returns the last item from my_list, or by providing the index of the item we want to remove my_list.pop(index), which removes and returns the item at that index.
list2 = [25.50, True, -55, 1+2j]
print("Original list:", list2)
list2.pop(2)
print("List after popping:", list2)
Output:
Original list: [25.5, True, -55, (1+2j)]
List after popping: [25.5, True, (1+2j)]
clear() MethodThe clear() method in Python is used to remove all elements from a list, leaving it empty.
We can remove all list items using the clear() method by calling it on the list object like my_list.clear(), which empties my_list, leaving it with no elements.
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print("Cleared list:", my_list)
Output:
Cleared list: []
del KeywordThe del keyword in Python is used to delete an element either at a specific index or a slice of indices from memory.
We can remove list items using the del keyword by specifying the index or slice of the items we want to delete, like del my_list[index] to delete a single item or del my_list[start:stop] to delete a range of items.
list1 = ["a", "b", "c", "d"]
print("Original list:", list1)
del list1[2]
print("List after deleting:", list1)
Output:
Original list: ['a', 'b', 'c', 'd']
List after deleting: ['a', 'b', 'd']
list2 = [25.50, True, -55, 1+2j]
print("List before deleting:", list2)
del list2[0:2]
print("List after deleting:", list2)
Output:
List before deleting: [25.5, True, -55, (1+2j)]
List after deleting: [-55, (1+2j)]
