There are a few ways to remove an item from a list by its index. Firstly you can use the del
keyword and point that to a list index.
fruit = ['Potato', 'Apple', 'Banana', 'Cucumber', 'Onion', 'Orange', 'Carrot']
del fruit[0]
print(fruit)
# ['Apple', 'Banana', 'Cucumber', 'Onion', 'Orange', 'Carrot']
del fruit[-1] # negative index removes from end of list
print(fruit)
# ['Apple', 'Banana', 'Cucumber', 'Onion', 'Orange']
del fruit[2:4] # Delete a range with slice notation
print(fruit)
# ['Apple', 'Banana', 'Orange']
The second way to remove an item by index is to use the list's pop()
method which returns the item that has been removed from the list, for example:
fruit = ['Apple', 'Banana', 'Orange', 'Broccoli'] removed = fruit.pop(3) print(fruit) # ['Apple', 'Banana', 'Orange'] print(removed) # Broccoli