How do you remove a specified value from a list in Python?

There are two ways to remove a specified value from a list:

  1. Utilize the remove() method:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)

Output:

[1, 2, 4, 5]
  1. 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]
广告
Closing in 10 seconds
bannerAds