Remove Element by Value in Python

Remove the first occurrence of a value from a list, if present.

BeginnerList ProgramsExample 21 of 25
remove-element-by-value.py
1# Program to remove first occurrence of a value from list
2
3items = input("Enter list elements separated by space: ").split()
4value = input("Enter value to remove: ")
5
6if value in items:
7 items.remove(value)
8 print("Updated list:", items)
9else:
10 print("Value not found in list.")

Output

Enter list elements separated by space: 1 2 3 2
Enter value to remove: 2
Updated list: ['1', '3', '2']

What's going on

We use the list method .remove() which deletes the first matching element.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.