Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to delete an element from a list in Python

Anusheh Zohair Mustafeez

When working with lists, one often needs to remove certain elements from them permanently. Luckily, Python provides many different yet simple methods to remove an element from a list.

remove()

remove() deletes the first instance of a value in a list. This method should be used when one knows exactly which value they want to delete regardless of the index. The code below demonstrates this:

l = [1, 4, 6, 2, 6, 1]

print("List before calling remove function:")
print(l)

l.remove(6)

print("List after calling remove function:")
print(l)

del

del can be used to delete a single index of a list, a slice of a list, or the complete list. For this shot, let’s look at how we can delete a value at a certain index with the del keyword:

l = [1, 4, 6, 2, 6, 1]

print("List before calling del:")
print(l)

del l[3]

print("List after calling del:")
print(l)

pop()

The pop method removes an element at a given index and returns its value. The code below shows an example of this:

l = [1, 4, 6, 2, 6, 1]

print("List before calling pop function:")
print(l)

print(l.pop(4))

print("List after calling pop function:")
print(l)

Note: The argument passed to the pop method is optional. If not passed, the default index (-1) is passed as an argument so the last element in the list is removed.

RELATED TAGS

python

CONTRIBUTOR

Anusheh Zohair Mustafeez
RELATED COURSES

View all Courses

Keep Exploring