How to to remove an element from an array or list
Published on Aug. 22, 2023, 12:16 p.m.
In Python, you can use the remove()
function or the pop()
function to remove an element from an array or list.
The remove()
function can be used to remove a specific element, as shown below:
my_list = [1, 2, 3, 4]
my_list.remove(2) # remove element 2
print(my_list) # [1, 3, 4]
The pop()
function can be used to remove an element by its index in the list, as shown below:
my_list = [1, 2, 3, 4]
my_list.pop(2) # remove element at index 2 (i.e., 3)
print(my_list) # [1, 2, 4]
If you don’t specify an index for pop()
, it will remove the last element from the list by default.
Please note that these functions modify the original list, so use them with caution.