How to remove an item from a list in Python? (clear, pop, remove, del)

Authors

In Python, you can use list methods clear(), pop(), and remove() to remove items (elements) from a list.

You can also delete items using del statement by specifying a position or range with an index or slice.

clear() - Remove all items.

pop() - Remove an item by specifiy an index and get its value.

remove() - Remove an item by value.

del - Remove items by index or slice

clear() - Remove all items

You can remove all items from the list with clear().

l = [0, 1, 2]

l.clear()
print(l)
# []

pop() - Remove an item by specifiy an index and get its value.

You can remove the item at the specified position and get its value with pop().

The index at the start is 0 (zero-based indexing).

l = [0, 1, 2, 3, 4, 5]

print(l.pop(0))
# 0

print(l)
# [1, 2, 3, 4, 5]

print(l.pop(3))
# 4

print(l)
# [1, 2, 3, 5]

You can specify the position from the end by using negative values to.

The index at the end is -1.

# [1, 2, 3, 5]

print(l.pop(-2))
# 3

print(l)
#[1, 2, 5]

If you leave the argument for the pop function, the last item will be deleted and returned.

print(l.pop())
# 5

print(l)
# [1, 2]

remove() - Remove an item by value.

You can remove the first item from the list where its value is equal to the specified value with remove().

l = ['Apple', 'Banana', 'Grape', 'Banana', 'Orange']

l.remove('Apple')
print(l)
# ['Banana', 'Grape', 'Banana', 'Orange']

If there is more than one item in the list matching the specified value, only the first is deleted.

l.remove('Banana')
print(l)
# ['Grape', 'Banana', 'Orange']

If you try remove an item that does not exist in the list an error will be raised.

l.remove('Lemon')
# ValueError: list.remove(x): x not in list

You can use in to check if the list contains the item.

del - Remove items by index or slice

clear(), pop(), and remove() are methods of list.

You can also remove items from a list with del.

Specify the item to be deleted by index.

The first index is 0, and the last is -1.

l = [0, 1, 2, 3, 4, 5]

del l[0]
print(l)
# [1, 2, 3, 4, 5]

del l[3]
print(l)
# [1, 2, 3, 5]

del l[-1]
print(l)
# [1, 2, 3]

del l[-2]
print(l)
# [1, 3]

You can also delete multiple items using a slice.

l = [0, 1, 2, 3, 4, 5]
del l[2:5]
print(l)
# [0, 1, 5]

l = [0, 1, 2, 3, 4, 5]
del l[:3]
print(l)
# [3, 4, 5]

l = [0, 1, 2, 3, 4, 5]
del l[-2:]
print(l)
# [0, 1, 2, 3]

You can delete all items by specifying the entire range.

l = [0, 1, 2, 3, 4, 5]
del l[:]
print(l)
# []

You can also use a step like [start:stop:step].

l = [0, 1, 2, 3, 4, 5]
del l[::2]
print(l)
# [1, 3, 5]
TrackingJoy