Python remove() Function

The remove() function in Python is used to remove the first occurrence of an element with specified value, from a list. For example:

a = [13, 34, 54, 67, 34, 54]
a.remove(34)
print(a)

Following is the output produced by above Python program, demonstrating the remove() function:

[13, 54, 67, 34, 54]

Python remove() Function Syntax

The syntax of remove() function is:

listName.remove(element)

Python remove() Function Example

Here is a simple example of remove() function in Python. This program allows user to remove the particular element from the list:

a = [13, 34, 54, 67, 34, 54]
print("The list is:")
print(a)

print("\nEnter an element to remove: ", end="")
element = int(input())
a.remove(element)

print("\nNow the list is:")
print(a)

The snapshot given below shows the sample run of above program, with user input 67 as value or element to delete from the list:

python remove function

Now the problem is, what if user enters an element that does not exist in the list ?
In that case, the function remove() raises an exception named ValueError. For example, here is another sample run of above program, but with an element input that does not exist in the list say 500:

python remove function example

Therefore to handle this exception, we need to wrap the function inside the try block to catch the exception using the except block as shown in the program given below:

a = [13, 34, 54, 67, 34, 54]
print("The list is:")
print(a)

print("\nEnter an element to remove: ", end="")
element = int(input())
try:
    a.remove(element)
    print("\nNow the list is:")
    print(a)
except ValueError:
    print("\nThe element does not exist!")

Now the output with same user input as of previous sample run, will exactly be:

python remove function program

This is the last program of this article, allows user to define the size of list, along with its elements, and the element to remove:

print("Enter the size of list: ", end="")
s = int(input())
print("Enter", s, "elements: ", end="")
x = []
for i in range(s):
    val = input()
    x.append(val)

print("\nThe list is:")
for i in range(s):
    print(x[i], end=" ")

print("\n\nEnter an element to remove: ", end="")
e = input()
try:
    x.remove(e)
    print("\nNow the list is:")
    for i in range(len(x)):
        print(x[i], end=" ")
except ValueError:
    print("\nInvalid Input!")

The snapshot given below shows the sample run:

python remove function codes

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋