How to Remove an Element From a Python List Using Its Index?
There are several ways to remove an element from a Python list using its index:
Method 1: Using the del
statement
You can remove an element from a list by using the del
statement followed by the index position of the element you want to delete. Here's an example:
my_list = ['apple', 'banana', 'orange', 'kiwi']
del my_list[2] # remove the element at index position 2
print(my_list) # output: ['apple', 'banana', 'kiwi']
Method 2: Using the pop()
method
The pop()
method removes the element at the specified index and returns it. If you don't specify an index, it removes and returns the last element in the list. Here's an example:
my_list = ['apple', 'banana', 'orange', 'kiwi']
my_list.pop(1) # remove the element at index position 1 (banana)
print(my_list) # output: ['apple', 'orange', 'kiwi']
Method 3: Using the remove()
method
The remove()
method removes the first occurrence of the specified element from the list. You need to pass the value of the element as an argument, not its index position. Here's an example:
my_list = ['apple', 'banana', 'orange', 'kiwi']
my_list.remove('orange') # remove the element 'orange'
print(my_list) # output: ['apple', 'banana', 'kiwi']