Python List remove() (2024)

The remove() method removes the first matching element (which is passed as an argument) from the list.

Example

# create a listprime_numbers = [2, 3, 5, 7, 9, 11]

# remove 9 from the listprime_numbers.remove(9)

# Updated prime_numbers Listprint('Updated List: ', prime_numbers)# Output: Updated List: [2, 3, 5, 7, 11]

Syntax of List remove()

The syntax of the remove() method is:

list.remove(element)

remove() Parameters

  • The remove() method takes a single element as an argument and removes it from the list.
  • If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.

Return Value from remove()

The remove() doesn't return any value (returns None).

Example 1: Remove element from the list

# animals listanimals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removedanimals.remove('rabbit')

# Updated animals Listprint('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'guinea pig']

Example 2: remove() method on a list having duplicate elements

If a list contains duplicate elements, the remove() method only removes the first matching element.

# animals listanimals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']

# 'dog' is removedanimals.remove('dog')

# Updated animals listprint('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'guinea pig', 'dog']

Here, only the first occurrence of element 'dog' is removed from the list.

Example 3: Deleting element that doesn't exist

# animals listanimals = ['cat', 'dog', 'rabbit', 'guinea pig']

# Deleting 'fish' elementanimals.remove('fish')

# Updated animals Listprint('Updated animals list: ', animals)

Output

Traceback (most recent call last): File ".. .. ..", line 5, in <module> animal.remove('fish')ValueError: list.remove(x): x not in list

Here, we are getting an error because the animals list doesn't contain 'fish'.

Also Read:

Python List remove() (2024)
Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5752

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.