Remove elements from a Python List

  • November 27, 2022
  • python
JOIN Clause

There are three methods to remove elements from a list:

  • Making use of the remove() method
  • Using the pop() method of the list object
  • Using the del operator
remove() method:

The list includes a built-in method for Python called removes (). Removing the first element that matches the given criteria from the list is helpful.

Syntax:

list.remove(element)

The element that you want to remove from the list.

ReturnValue

There is no return value for this method.

For instance,

List = ['A', 'E', 'I', 'O','U']
List.remove('I')
print(List)

Output:

['A', 'E', 'O', 'U']
pop() method:
  • Another frequently used method for list objects is pop(). This method returns the item or element that was removed from the list.
  • The item to be removed must be specified in the remove() method, which is how this method differs from remove().
  • However, when using the pop() function, the item’s index is passed in as an argument, which causes the item to be returned to the specified index.
  • An IndexError is raised if the specified item to be removed cannot be found.

Example:

List = ["CAT",11,22,33,"JAVA",22,33,11]
List.pop(1)
print(List)

Output:

['CAT', 22, 33, 'JAVA', 22, 33, 11]
del operator:

With one exception, this operator differs significantly from the pop() method of the List object. The item or element at the specified index location is removed from the list by the del operator, but unlike the pop() method, the item is not returned.

Example:

List = ["CAT",11,22,33,"JAVA",22,33,11]
del List[1]
print(List)

Output:

['CAT', 22, 33, 'JAVA', 22, 33, 11]

Note: also read about Iterate over a list in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *