'How to delete all elements only that i want?

I'm really beginer of python and i'm wondering how to remove all same elements that i want

I know i can remove a one element with list.remove('target') but it just happen once,

I googled about it but they just say use 'for' or 'while' but i don't know how to do it with a smart way

example , when i have list "apple" i want to make it "ale" with parameter'p'

I tried

list = ['a','p','p','l','e']
    for i in list:
       list.remove('p')

but i got error that 'ValueError: list.remove(x): x not in list'

(My English might sucks because i'm Korean :( and it's my first ask in stackoverflow )



Solution 1:[1]

First you should not be using list as a variable name as list is a built-in type in python.

See: Built-in types in python

For your question, you can use list comprehension for this. eg:

my_list = ['a','p','p','l','e']
element_to_remove = 'p'
new_list = [item for item in my_list if item != element_to_remove]
# new_list = ['a', 'l', 'e']

Solution 2:[2]

You can convert the list to set (so that there will be no repetitions) and convert it back to list. After, remove the element you want.

my_list = ['a','p','p','l','e']
my_list2 = my_list(set(my_list))
my_list.remove('p')

Solution 3:[3]

Try list comprehension:

[i for i in l if i not in ('p',)]

where l is your list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iR0ckY
Solution 2 Daniel Reuveni
Solution 3 Jacek Błocki