AppDividend
Latest Code Tutorials

Python List remove() | How to Remove an item from a List

0

Python list remove() is an inbuilt function that searches for the element in the List and removes the first matching item. The remove() method does not return any value but removes the given object from the List. A list is the collection of arbitrary objects, like an array in many other programming languages, but more flexible than an array. Lists are defined by enclosing a comma-separated series of items in square brackets ([ ]),

Understanding Python List remove()

In Python,  Integer or float objects, for example, are primitive data types that can’t be further mutilated. These data types are immutable, meaning that they can’t be modified once they have been assigned. It doesn’t make any sense to think of changing the value of an integer. If you need a different integer, then you just assign a different one. No need to modify the existing one.

In the case of the Python list, they are mutable. Once a list has been created, new items can be added, shifted, deleted, and moved around at will. Python language provides a wide range of ways to modify the lists. For example, you can append an item, extend an item, or even remove an item from the list. The List is the container of different objects.

The List remove() is one of those methods that can modify the List. The remove() method deletes an item or items from the List.

Syntax

The syntax of the List remove() method is the following.

list.remove(item)

Parameters

The remove() method takes a single element as an argument and removes it from the List.

The item parameter is required, and any type (string, number, List) the element you want to remove. The remove() method only removes the given element from the List.

Return Value

It doesn’t return any value.

Example

Let us take a simple example.

// app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
GoT.remove('Jon')
print(GoT)

In the above example, we are removing the Jon element.

Python List Remove Example | remove() Method Tutorial

Trying to remove the element that doesn’t exist.

Let us remove an item that does not exist in the List and see what we get in the output.

// app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
GoT.remove('Arya')
print(GoT)

Trying to Delete Element That Doesn't Exist

If the element(argument) passed to the remove() method doesn’t exist, ValueError exception is thrown. So, the List remove() method removes the element which is passed as an argument.

Removing multiple elements from the List

To remove multiple elements from the list, we can use while() and List.remove() method.

listRep = [19, 21, 18, 18, 46, 21, 11]

while 18 in listRep:
    listRep.remove(18)

print(listRep)

Output

[19, 21, 46, 21, 11]

In the above example, 21 and 18 are the two elements that appear more than one time.

Now, if we have removed 18, that appears twice in the List with while condition.

In the output, you can see that 18 is removed from the list.

Different ways to remove an item from the list in Python

In Python, there are different ways, and you can remove the item from the list.

  1. Removing all elements using list clear()
  2. Removing an element by index using list pop()
  3. Removing elements by index or slice using del keyword
  4. Removing multiple elements that meet the condition: List comprehension

Removing all elements using list clear()

Python list clear() is an inbuilt function that removes all the items from the list. It empties the list.

Syntax

list.clear()

Parameters

The clear() method does not take any parameter.

Return Value

The clear() method only empties the given list. It doesn’t return any value.

Example

listRep = [19, 21, 18, 18, 46, 21, 11]
listRep.clear()
print(listRep)

Output

[]

You can see that it completely clears the list and does not leave the single item on the list.

Removing an item by index using list.pop()

The pop() method deletes the item at the given index from the list and returns the removed object.

Syntax

list.pop(index)

Parameters

The pop() method takes a single argument, which is the index of the list. The argument passed to a pop() method is optional. If you don’t pass, then the default index -1 is passed as an argument, which is the index of the last item. If the passed index is not in range, then it throws IndexError: pop index out of range exception.

Return Value

The list.pop() method returns the removed item from the list.

Example

listRep = [19, 21, 18, 46, 11]
removedElement = listRep.pop(3)
print('The list is: ', listRep)
print('The removed element is: ', removedElement)

Output

The list is:  [19, 21, 18, 11]
The removed element is:  46

In this example, we have passed 3 as an index. Remember, the list index starts from 0.

So, at index 3, 46 item is present. So the pop() method removes that element from the list and returns as removedElement, and we printed the list as well as the removedElement. From the list, you can see that the item has been removed.

The pop() method is useful when you have to remove a particular element from a list in real-time applications like remove the customer data based on the id.

If we specify the nonexistent index, then it will raise an error.

listRep = [19, 21, 18, 46, 11]
removedElement = listRep.pop(8)
print('The list is: ', listRep)
print('The removed element is: ', removedElement)

Output

Traceback (most recent call last):
  File "app.py", line 2, in <module>
    removedElement = listRep.pop(8)
IndexError: pop index out of range

You can see that we don’t have any element in the 8th position of the list. That is why it throws an exception saying that IndexError: pop index out of range.

Removing elements by slice using del in Python

The Python del method deletes all the elements in the range, starting from index ‘a’ till ‘b’ provided in the arguments.

Syntax

del list[start index: end index]

The del is a statement that takes the start index from which we have to start removing the list and end index until we need to stop removing. 

One thing to remember that while removing the elements, it counts the start index but not the end index. The last removed element’s index is end index – 1. It does not include the end index.

Example

listRep = [19, 21, 18, 46, 11]
del listRep[1:4]
print('The list is: ', listRep)

Output

The list is:  [19, 11]

From the output, you can see that we have removed the multiple items from the list using a del statement. The range of indexes is 1 to 4. That means the start index is 1, which includes the 21 element. Now our end index is 4, and 11 item is at 4th position, but it does not remove that. That means the removed elements’ indexes are 1, 2, 3.

If you want to clear the entire Python list or delete all items, then you can do that by specifying the whole range.

listRep = [19, 21, 18, 46, 11]
del listRep[:]
print('The list is: ', listRep)

Output

The list is:  []

You can see that it clears the list.

You can also specify the step as [start: stop: step].

Let’s remove the even elements from the list.

listRep = list(range(20))
del listRep[2: 20: 2]
print('The list is: ', listRep)

Output

The list is:  [0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

First, we have created a list using Python range() function and then removed the items using the del statement and list slice.

Removing multiple list items that meet the condition

Removing items that satisfy the condition is equivalent to extracting items that do not satisfy the condition. And that is why the list comprehensions are used. An example of removing odd or even items (= keeping even or odd items) is as follows. The % Is the remainder operator, and i % 2 is the remainder of dividing i by 2.

In the list comprehension, a new list is generated. Unlike the list type method or del statement introduced so far, the original list is not changed.

listRep = list(range(20))
print(listRep)

print('Remove all the odd elements using list comprehension')
print([i for i in listRep if i % 2 == 0])

print('Remove all the even elements using list comprehension')
print([i for i in listRep if i % 2 != 0])

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Remove all the odd elements using list comprehension
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Remove all the even elements using list comprehension
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

This method is more of a filter method in which you filter out the unwanted elements from the list. 

Conclusion

In this tutorial, we have seen how to remove the items from the list, clear the list, or remove the specific element or range of elements using remove(), clear(), pop(), del statement, and list comprehension.

Finally, Python List remove() function example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.