Editor

Python Program to Remove an Element from a List

Beginner · Lists

Python has three common ways to remove an element from a list: remove() deletes by value, pop() deletes by position and returns the element, and del deletes by position. This program uses all three and shows how to avoid the error that remove() raises for a missing value.

Program

remove_element_from_list.py
fruits = ["apple", "banana", "cherry", "banana", "mango"]
print("Original list:", fruits)
# remove() deletes the first matching value
fruits.remove("banana")
print('After remove("banana"):', fruits)
# pop() deletes by index and gives the element back
removed = fruits.pop(1)
print("After pop(1):", fruits, "| removed:", removed)
# del deletes by index
del fruits[0]
print("After del fruits[0]:", fruits)
# remove() raises an error for a missing value, so check first
item = "grape" # or: item = input("Enter the item to remove: ")
if item in fruits:
fruits.remove(item)
print("Removed", item)
else:
print(item, "is not in the list, so nothing was removed")
Output
Original list: ['apple', 'banana', 'cherry', 'banana', 'mango']
After remove("banana"): ['apple', 'cherry', 'banana', 'mango']
After pop(1): ['apple', 'banana', 'mango'] | removed: cherry
After del fruits[0]: ['banana', 'mango']
grape is not in the list, so nothing was removed

How it works

  1. remove("banana") deletes only the first "banana"; the second one stays in the list.
  2. pop(1) deletes the element at index 1 and returns it, so it can be saved in removed. With no index, pop() removes the last element.
  3. del fruits[0] deletes the element at index 0 and returns nothing.
  4. fruits.remove("grape") would stop the program with a ValueError, so the in check runs first.

Another way to write it

Removing every copy of a value

Removing every copy of a value
numbers = [3, 3, 5, 3, 8]
# The trap: removing inside a for loop skips the next element
broken = numbers.copy()
for n in broken:
if n == 3:
broken.remove(n)
print("Removing inside a for loop:", broken)
# The fix: build a new list that leaves the value out
cleaned = [n for n in numbers if n != 3]
print("Using a list comprehension:", cleaned)
Output
Removing inside a for loop: [5, 3, 8]
Using a list comprehension: [5, 8]

When an element is removed, everything after it shifts left, so the loop jumps over the next element and one 3 survives. Building a new list avoids the problem.

Try it yourself

Change item to "mango" and run the program to see it removed.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises