Python List remove() Method Tutorial

In this section, we will learn what the List remove() method is and how to use it in Python.

Remove an Item from a List Python

The Python list remove() method is used to remove the first occurrence of a specific value from a list.

Basically, this method takes a value as its argument and then looks for that value in the target list to find the first occurrence of this value. If it found one, it will be removed.

List remove() Method Syntax:

list.remove(value)

List remove() Method Parameter:

The method takes one argument and that is the value we want to remove its first occurrence in the target list object.

List remove() Method Return Value:

The method does not return a value.

Note: If the specified value was not in the list, you’ll get an exception!

Example: python remove element from a list

li = ["ItemOne","ItemTwo","ItemThree","ItemOne","ItemTwo","ItemThree"]

print(li.remove("ItemTwo"))

Output:

None

Python remove duplicate from a list

The easiest way of removing duplicate content from a list is by using the set() function (In short, the job of this function is to remove the duplicate elements) and passing a reference of the list to this function and then pass the returned object of the set() function to the list() function to get a new list object at the end.

Example: removing duplicate from a list in python

li = ["ItemOne","ItemTwo","ItemThree","ItemOne","ItemTwo","ItemThree"]

print("Before calling the set() function: ")

print(li)

li = list(set(li))

print("After calling the set() function:")

print(li)

Output:

Before calling the set() function:

['ItemOne', 'ItemTwo', 'ItemThree', 'ItemOne', 'ItemTwo', 'ItemThree']

After calling the set() function:

['ItemTwo', 'ItemThree', 'ItemOne']
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies