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
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 removedHow it works
remove("banana")deletes only the first "banana"; the second one stays in the list.pop(1)deletes the element at index 1 and returns it, so it can be saved inremoved. With no index,pop()removes the last element.del fruits[0]deletes the element at index 0 and returns nothing.fruits.remove("grape")would stop the program with aValueError, so theincheck runs first.
Another way to write it
Removing every copy of a value
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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
- Remove Duplicates from a List
- a Menu-Driven List
- Move All Zeros to the End of a List
- Copy a List
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Find the Sum of Elements in a List
- Reverse a List
- Count Occurrences of an Element in a List
All Python programs · CBSE class 12 practical file · Python exercises