Low Orbit Flux Logo 2 F

Python How To Delete Element From List

It is pretty straightforward to delete an element from a list in Python. Unsurprisingly there are multiple ways to do this. Each method is usually a bit different.

To remove an element from a list by index just use the following:


a = ["kiwi", "pinecone", "sand", "tree"]
del a[2]

This just removes whatever element was at the specified index.

Remove the first matching element:


a = ["kiwi", "pinecone", "sand", "tree"]
a.remove("pinecone")

This will remove the first element that matches the specified parameter. It only removes the first matching element. If additional elements exist in the list they will not be removed.

Remove an item at a given index and return it with pop():


a = ["kiwi", "pinecone", "sand", "tree"]
x = a.pop(2)

This will remove whatever element is at the given index. It also returns that element so that it can be assigned and used.

Clear a list:


a = ["kiwi", "pinecone", "sand", "tree"]
a.clear()

This will remove all elements from a list but the actual list variable will still exist.

Delete an entire list:


a = ["kiwi", "pinecone", "sand", "tree"]
del a

The above will remove the entire list.