How do you remove a specified value from a list in Python?
There are two ways to remove a specified value from a list:
- Utilize the remove() method:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)
Output:
[1, 2, 4, 5]
- Use list comprehension:
my_list = [1, 2, 3, 4, 5]
value_to_remove = 3
my_list = [x for x in my_list if x != value_to_remove]
print(my_list)
Output:
[1, 2, 4, 5]