How to remove a specific element from a Python list?

To remove a specific element from a Python list, you can either use the remove() method or a list comprehension.

Use the remove() method:

my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)  # Output: [1, 2, 4, 5]

Using list comprehensions:

my_list = [1, 2, 3, 4, 5]
my_list = [x for x in my_list if x != 3]
print(my_list)  # Output: [1, 2, 4, 5]
bannerAds