Python list remove() method

How to use list remove() method in Python:

list remove method is used to remove the first matching element of a python list. This method takes one value as its argument and removes the first element that matches the argument.

In this post, we will learn how to use list remove() with examples.

Syntax of list remove():

Below is the syntax of list remove() method:

list.remove(element)

This method doesn’t return any value. Also, the element should be in the list. Otherwise, it will throw ValueError.

Example 1: Example to use remove() on a list of items:

Let’s take a look at the below example program:

given_list = [1, 2, 3, 4, 5]

given_list.remove(3)

print('List after item is removed : {}'.format(given_list))

Here,

  • given_list is the original list. It called remove to remove the element 3 from the list.
  • The final print statement is printing the list after the item is removed.

If you run this script, it will print the below output:

List after item is removed : [1, 2, 4, 5]

As you can see here, the item 3 is removed from the list.

Example 2: use remove() to remove on list of items with duplicate items:

Let’s consider the below program:

given_list = [1, 2, 3, 4, 5, 3]

given_list.remove(3)

print('List after item is removed : {}'.format(given_list))

In this program, we are removing 3 from the list given_list. But, given_list has two 3. As per the definition, it will remove the first 3 and print the below output:

List after item is removed : [1, 2, 4, 5, 3]

Example 3: Using remove() with an invalid item:

Let’s consider the below program:

given_list = [1, 2, 3, 4, 5, 3]

given_list.remove(13)

print('List after item is removed : {}'.format(given_list))

It is trying to remove 13 from the list, but 13 is not in the list.

It will throw a ValueError.

    given_list.remove(13)
ValueError: list.remove(x): x not in list

You might also like: