Categories: python

Remove elements from a Python List

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

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago