Join our newsletter for the latest updates.

Python Program to Differentiate Between del, remove, and pop on a List

In this example, you will learn to differentiate between del, remove, and pop on a list.

To understand this example, you should have the knowledge of the following Python programming topics:


Use of del

del deletes items at a specified position.

my_list = [1, 2, 3, 4]

del my_list[1]

print(my_list)

Output

[1, 3, 4]

del can delete the entire list with a single statement whereas remove() and pop() cannot.

my_list = [1, 2, 3, 4]

del my_list

print(my_list)

Output

NameError: name 'my_list' is not defined

Moreover, it can also remove a specific range of values, unlike remove() and pop().

my_list = [1, 2, 3, 4]

del my_list[2:]

print(my_list)

Output

[1, 2]

Error mode

If the given item is not present in the list, del gives an IndexError.

my_list = [1, 2, 3, 4]

del my_list[5]

print(my_list)

Output

IndexError: list assignment index out of range

Use of remove

remove() deletes the specified item.

my_list = [1, 2, 3, 4]

my_list.remove(2)

print(my_list)

Output

[1, 3, 4]

Error mode

If the given item is not present in the list, del gives an ValueError.

my_list = [1, 2, 3, 4]

my_list.remove(15)

print(my_list)

Output

ValueError: list.remove(x): x not in list

Use of pop

pop() removes the item at a specified position and returns it.

my_list = [1, 2, 3, 4]

print(my_list.pop(1))

print(my_list)

Output

2
[1, 3, 4]

Error mode

If the given item is not present in the list, del gives an IndexError.

my_list = [1, 2, 3, 4]

my_list.pop(5)

print(my_list)

Output

IndexError: pop index out of range

If you want to learn more about these individual methods/statements, you can learn at Python del Statement, Python List remove() - Programiz, and Python List pop() - Programiz.