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
Run in browser
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.