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

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 day ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago