How to remove an element from a list in Python?
Published on Aug. 22, 2023, 12:17 p.m.
There are several methods you can use to remove an element from a list in Python:
- Using the
remove()method - this method removes the first occurrence of the specified element from the list:
my_list = [1, 2, 3, 4, 5]
my_list.remove(2)
print(my_list)
Output:
[1, 3, 4, 5]
In this example, we use the remove() method to remove the element 2 from the list my_list. The resulting list is [1, 3, 4, 5].
- Using the
delkeyword - this method removes the element at a specified index from the list:
my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list)
Output:
[1, 2, 4, 5]
In this example, we use the del keyword to remove the element at index 2 (which is the third element) from the list my_list. The resulting list is [1, 2, 4, 5].
- Using the
pop()method - this method removes the element at a specified index from the list and returns it:
my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop(2)
print(my_list)
print(popped_element)
Output:
[1, 2, 4, 5]
3
In this example, we use the pop() method to remove the element at index 2 (which is the third element) from the list my_list. The removed element is returned by the pop() method and stored in the variable popped_element. The resulting list is [1, 2, 4, 5].