Python Program to Remove an Item from a List

A list in the Python programming language is a mutable object that allows adding or deleting items. In this article, we will demonstrate how to write a Python program to remove an item from a List with examples.

When working with Python lists, removing list items is a common task, and there are numerous options to accomplish this task. For instance, the Python programming language has built-in functions to remove a list item, including remove(), pop(), clear() methods, and the del statement. These are predefined functions that we can use to remove list items.

Apart from those built-in functions, we can use the custom code to remove list items. It includes for and while loops, list comprehensions, filters, and a lambda statement to remove one item or multiple items based on a condition.

Python Program to remove list item using built-in functions

In this section, we utilize the built-in list methods such as remove(), pop(), clear(), and del.

Python Program to Delete a List Item using the remove() function

If you know the value that you want to delete, use the remove() function. The built-in remove() method accepts a single parameter value and searches for the first occurrence of it. Once it finds it, delete that item from the list. If it doesn’t find, it raises a ValueError. When there are multiple occurrences of an item, the remove() function deletes the first occurrence and ignores the others.

Syntax

myList.remove(element)

NOTE: From an interview perspective, if the person asks to write a program to remove a list item by value. Otherwise, program to remove the first occurrence of an item in a list. Here, we must use the Python remove() function to remove an item by value or the first occurrence of a list item.

In the program below, we declared an integer list with eight numbers. The first statement removes 25 from the list, and the print statement displays the list of remaining items.

As we all know, the remove() function accepts a single argument; to remove multiple items, we must call the same remove() function multiple times. The next line deletes 10 from a list.

a = [5, 10, 15, 20, 25, 30, 35, 40]

a.remove(25)
print(a)

a.remove(10)
print(a)
[5, 10, 15, 20, 30, 35, 40]
[5, 15, 20, 30, 35, 40]

Python Program to remove a list item using the pop() method

The pop() function accepts a single parameter, and it is completely optional. If we use it without any argument, the pop() function removes the last list item. If we pass an index position, it removes the list item at that position.

As we said earlier, the list pop() function uses the index value as a parameter. If you know the index position of the item that you want to remove, use the pop() method.

Syntax

myList.pop() # removes last item
myList.pop(index) # removes item at the index position.

In the example below, we declared an integer list. This Python program uses the pop() function to remove list items based on the index. To better understand it, we have shown multiple examples along with printing the popped-out value. 

  • a = n.pop(0) removes the item at the first index position and stores it in the variable a.
  • b = n.pop(5) removes the item at the fifth index position and stores it in variable b.
  • c = n.pop(2) deletes the item at the second index position and stores it in variable c.

NOTE: For every list removal, the index positions update. For instance, 35 is at the 6th index position. However, after deleting the item at the 0th position, 35 moves to the 5th position.

n = [5, 10, 15, 20, 25, 30, 35, 40]

a = n.pop(0)
print(a)
print(n)

b = n.pop(5)
print(b)
print(n)

c = n.pop(2)
print(c)
print(n)
5
[10, 15, 20, 25, 30, 35, 40]
35
[10, 15, 20, 25, 30, 40]
20
[10, 15, 25, 30, 40]

Apart from the positive value, you can also try using the negative index values as the pop() method arguments. Here, -1 removes the last item from the list. If you use the Python pop() function without any argument, it removes the last list element by default.

n = [5, 10, 15, 20, 25, 30, 35, 40]

a = n.pop(-1)
print(a)
print(n)

b = n.pop(-3)
print(b)
print(n)

c = n.pop()
print(c)
print(n)
40
[5, 10, 15, 20, 25, 30, 35]
25
[5, 10, 15, 20, 30, 35]
35
[5, 10, 15, 20, 30]

Python Program to remove a list item using the del keyword

Similar to the pop() function, the delete/del keyword also uses the index value to remove the list items. However, the del statement allows you to place either a single index or a range of indices, like slicing.

Similar to the pop() function, the delete/del keyword also uses the index value to remove the list items. However, the del statement allows you to place either a single index or a range of indices, like slicing. It means to remove a single item by using its index position. When you need to remove multiple items or complete list elements, use the slicing technique.

Syntax

del myList[index] # remove one item
del myList[start:end] # remove items from start to end
del myList # delete complete list

In the Python program to remove list items below, we declared an integer list of ten elements. Next, we applied the possible options of the del keyword to remove list items. The first statement removes the list item at the third index position.

In the next line, we utilized the slicing technique to remove multiple list items. It deletes items starting from the second index position to the sixth position (2 to 6). 

Similarly, the last statement will remove all items from the list because we haven’t specified the start and end positions. The del keyword considers 0 as the start and len – 1 as the last index position. Hence, an empty list.

a = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

del a[3]
print(a)

del a[2:6]
print(a)

del a[:]
print(a)
[5, 10, 15, 25, 30, 35, 40, 45, 50]
[5, 10, 40, 45, 50]
[]

If we use the last index, the Python program removes all the existing list items and the list itself. Once the code below is executed, if you print or call n, it returns a NameError because the list does not exist.

n = [1, 2, 3]
del n

The following image shows the result of the built-in list methods: remove(), pop(), and the del keyword.

Python Program to Remove an item from a List

Python program to remove list items using the clear() method

The built-in clear() method accepts no arguments and removes all items in the existing list. In short, it empties the current list. If your goal is to remove all the existing items from a given list and keep the object, use the clear() method.

Syntax

myList.clear()

The following example uses the clear() method to remove all items in a list. As you can see from the output below, it returns an empty list ([]).

a = [1, 2, 3, 4, 5, 6, 7]
a.clear()
print(a)
[]

Best approach

The above-mentioned approaches are best suited for removing an item based on index position or value. However, if the index is wrong or the given value is not available, the above built-in list methods throw an error. So, we need a better approach.

The if statement in the Python program to remove list items below checks whether the value five exists in list a. If true, the pop() function will remove the first occurrence of 5 from the list. We can apply the same logic of an if statement to check for a value or index and then apply the list method.

a = [5, 10, 15, 5, 20, 25, 5, 30]
val = 5

if val in a:
    a.pop(a.index(val))

print(a)
[10, 15, 5, 20, 25, 5, 30]

Python Program to remove a list item using custom code

The above-mentioned approaches are best suited for removing an item based on index position or value. However, you can use either the above options or the approaches mentioned below (custom code) to remove a particular element from the list based on the given condition.

Python program to remove a list item by slicing

Using the del keyword with the start and stop index positions, we can delete a range of list items. Without using the del, we can also perform the same operations. However, we must assign an empty list using the = operator. 

In the following example, we declared an integer list of 8 items. In the following statement, we used the slicing technique with the start (2) and end (6) index positions. It means selecting list items starting at index position 2 (3rd element) and ending at the 5th index position (6).

The = operator assigns these items to an empty list, which means list items at the 2nd, 3rd, 4th, and 5th index positions are removed from the list.

n = [1, 2, 3, 4, 5, 6, 7, 8]
n[2:6] = []
print(n)
[1, 2, 7, 8]

Slicing vs del keyword

The Python slicing technique is not about removing a range of list items, which can be done with the del keyword. However, slicing options help replace a range of list items with completely new items.

The program below replaces four items from a given list with a completely new list of two items. In short, the slicing technique removes list items from the 3rd index position into the 6th position (a total of 4 items) and adds two new items (100 and 200) in those places. All the remaining items shift their places.

n = [1, 2, 3, 4, 5, 6, 7, 8]
n[3:7] = [100, 200]
print(n)
[1, 2, 3, 100, 200, 8]

Remove all list items by Slicing (alternative to clear())

As we mentioned earlier, in the Python programming language, we can use the list slicing technique to remove list items. If we omit the starting and the ending index positions, it removes all items from a list.

In the example below, we use slicing without mentioning the start and end indexes, which means it should apply to the entire list. Next, assigned it to an empty result, resulting in clearing all list items.

n = [1, 2,3, 4, 5]
n[:] = []
print(n)
[]

Python Program to Remove a List Item using List Comprehension

It is the most popular and advanced approach for removing any particular list element. With list comprehension, we can remove an item by its value or condition. Whether you want to remove a list item or filter the list data based on a condition, use the list comprehension.

To demonstrate the advanced technique, we declared an integer array of eight elements. Next, the list comprehension with a for loop iterates over the list items from the start to the end. The if condition (n != 5) checks whether each list item is not equal to 5; if True, assign that item to the list. In short, it removes all occurrences of 5 from a given list.

a = [5, 10, 15, 5, 20, 25, 5, 30]

a = [n for n in a if n != 5]
print(a)
[10, 15, 20, 25, 30]

In the above example, we used the list comprehension to remove all occurrences of a given value. However, we can use it to remove items based on a condition. For instance, the Python program to remove list items below removes odd numbers in the above list and keeps only the even numbers 10, 20, and 30. Here, the condition (n % 2 == 0) plays a crucial role. Whatever the condition, the result changes accordingly.

a = [n for n in a if n % 2 == 0]
print(a)
[10, 20, 30]

Similarly, you can try the code below to remove the even numbers from the given integer list and keep the odd values.

a = [n for n in a if n % 2 != 0]
print(a)
[5, 15, 5, 25, 5]

Python Program to Remove List Item Using filter()

The combination of the filter() function with a lambda statement acts like list comprehensions for iterating over list items. Here, the expression or the condition of the lambda statement helps to remove the list items. However, the filter() function returns a filter object. So, we must use the list() function to convert the filter object to a list.

This Python program uses the filter() and lambda statement to remove the list items based on the condition where the value equals 5.

a = [5, 10, 15, 5, 20, 25, 5, 30]

a = list(filter(lambda n : n != 5, a))
print(a)
[10, 15, 20, 25, 30]

Python program to remove duplicate items in a list

There are several ways to delete duplicate list items, and this section covers a few of them.

Using the set() function

As we all know, the set() function won’t allow any duplicate values, and if it finds any, it deletes them. The extra list() function converts a set to a list.

a = [5, 10, 15, 5, 20, 25, 5, 30]
a = list(set(a))
print(a)

[5, 10, 15, 20, 25, 30]

Using the for loop and the while loop

In this Python program to remove duplicate list items, we used the for loop to iterate over the list items. The while loop checks whether the count() of each item is greater than 1. If true, the list remove() function deletes those items. Here, we used the count() function to find out the total number of occurrences of each element in a list.

a = [5, 10, 15, 5, 20, 25, 5, 30]
for n in a:
    while a.count(n) > 1:
        a.remove(n)

print(a)

[10, 15, 20, 25, 5, 30]

Python Program to remove all occurrences of a list items

In the above example, the set() and the for loop will spare at least one value and remove the duplicates. However, the approaches mentioned below remove all occurrences of a given item from a list.

Using list comprehension

We used the count() function to get the total number of occurrences of each element in a list. Here, the list comprehension will print the list with a count exactly equal to one. It means removing all duplicates. The program below removes all items that are repeated more than once.

NOTE: If 3, 4, 5, or 6 are repeated more than once, they are removed from the list.

a = [1, 2, 3, 2, 4, 2, 2, 5, 6]

a = [n for n in a if a.count(n) == 1]
print(a)
[1, 3, 4, 5, 6]

Using a while loop

The following Python program uses the while loop to remove all occurrences of a list item. The while loop condition in the program below checks whether 2 is in the list. If true, use the remove() function to delete that item from a list. If there are any repeated elements other than 2, this program ignores them.

a = [1, 2, 3, 2, 4, 2, 2, 5, 6]

while 2 in a:
    a.remove(2)

print(a)
[1, 3, 4, 5, 6]

Using filter() function

a = [1, 2, 3, 2, 4, 2, 2, 5, 3]

a = list(filter(lambda n: n != 2, a))
print(a)
[1, 3, 4, 5, 3]

Using a for loop and an if statement

If you combine the Python pop() method with the for loop, you can remove all occurrences of list items. For instance, the program below uses a for loop enumerator to iterate over the list and capture the list value and the index position. The If statement checks whether the value equals five; if true, pop the index position.

a = [5, 10, 15, 5, 20, 25, 5, 30]

for i, n in enumerate(a):
    if n == 5:
        a.pop(i)

print(a)
[10, 15, 20, 25, 30]

This Python program uses the for loop to iterate and the remove() function to delete all occurrences of the integer five in a given list.

a = [5, 10, 15, 5, 20, 25, 5, 30]
val = 5

for i in a:
    if i == 5:
        a.remove(i)

print(a)
[10, 15, 20, 25, 30]

Python program to remove nested items from a list

Removing a particular item from a nested list is a work process. However, removing a sublist from a main list can be done using any of the above mentioned techqiues. Here, we used list comprehension to remove a nested list from a main list.

a = [1, 2, [3, 4], [5, 6], [3, 4], [7, 8]]

a = [n for n in a if n != [3, 4]]
print(a)
[1, 2, [5, 6], [7, 8]]