1

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 )

KingAnt
  • 11
  • 1
  • 1
    use a diff variable name instead of `list` since it's a buitlin datastruc – Avinash Raj Jan 24 '22 at 11:01
  • 1
    Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Thomas Weller Jan 24 '22 at 11:02
  • Um, i thank you for answering but i tired changing name right now that 'list' to 'myList' but it still doesn't work – KingAnt Jan 24 '22 at 11:08

3 Answers3

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']
devrraj
  • 312
  • 2
  • 7
0

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')
0

Try list comprehension:

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

where l is your list.

Jacek Błocki
  • 452
  • 3
  • 9