Home » Python

Python List remove() Method with Example

Python List remove() Method: Here, we are going to learn how to remove the first occurrence of the given element from the list using remove() method in Python?
Submitted by IncludeHelp, on December 15, 2019

List remove() Method

remove() method is used to remove the first occurrence of the given element, the method is called with this list (the list from which we have to remove the element) and accepts the element to be removed as an argument.

Syntax:

    list_name.remove(element)

Parameter(s):

  • element – It represents the element to be removed.

Return value:

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1:

# Python List remove() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before remove operations...")
print("cars: ", cars)

# removing "BMW"
cars.remove("BMW")
# removing "Audi"
cars.remove("Audi")

# printing the list 
print("cars after remove operations...")
print("cars: ", cars)

Output

cars before remove operations...
cars:  ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
cars after remove operations...
cars:  ['Porsche', 'Lexus', 'Audi']

Note: If any element doesn't exist in the list, method returns "ValueError".

Example 2:

# Python List remove() Method with Example

# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]

# printing the list
print("x before remove operations...")
print("x: ", x)

x.remove(10)   # will remove 10
x.remove(70)   # will remove 70

# printing the list
print("x after remove operations...")
print("x: ", x)

# removing an element that doesn't exist
# in the list...
x.remove(100) # will generate error

Output

x before remove operations...
x:  [10, 20, 30, 40, 50, 60, 70]
x after remove operations...
x:  [20, 30, 40, 50, 60]
Traceback (most recent call last):
  File "main.py", line 19, in <module>
    x.remove(100) # will generate error
ValueError: list.remove(x): x not in list





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.