89DEVs

Python list.remove() method

list.remove() method

The list.remove() method removes the first matching element from the given list. If the element occurs multiple times in the list, only the first occurrence is removed.

remove unique element from list

To remove a unique element from a list, use the remove() method as shown below. # remove unique element from list colors = ['green', 'yellow', 'red'] colors.remove('red') print(colors) In this example, the list colors contains three elements as string types: green, yellow and red. Then, the remove() method is called on the colors list and the argument red is passed to remove this value from the list. Finally, the modified list is printed and it contains the two remaining colors green and yellow. ['green', 'yellow']

remove duplicate elements from a list

If an element occurs multiple times in a list, only the first occurrence is removed by the remove() method. It is possible, to call the remove() method multiple times to remove duplicates from the list. # remove duplicate elements from a list colors = ['green', 'green', 'yellow', 'red'] colors.remove('green') print(colors) In this example, the list colors contains four elements as string values: twice the color green, the color yellow, and the color red. Then, the remove() method is called and the argument 'green' is passed to remove the first occurrence of green. Next, the modified list is printed and it contains all three colors once. ['green', 'yellow', 'red']

syntax of list.remove()

The syntax of list.remove() is: list.remove(value)

arguments of list.remove()

The list.remove() method accepts a single argument that is required. It is the value of the element to be removed from the list. If the value does not exist within the list, a ValueError exception is raised.

return value of list remove()

The list.remove() method doesn't return any value, it returns None.

time complexity of list.remove()

The time complexity of the list.remove() method is O(n).

related to list.remove()

The related function to the list.remove() method is the list.pop() method. The main difference is that pop() returns the element before it is removed. And pop() uses indexes, while remove() is value-based.

                
        

Summary


Click to jump to section