0

I want to remove all occurrences of a given element from a list but the problem is the way I'm doing I'm removing only half of it.

lsChars = ['x', 'y', 'a', 'a', 'a', 'a', 'b', 'c']

for c in lsChars:
    if c == "a":
        lsChars.remove(c)

print(lsChars)

The output is: ['x', 'y', 'a', 'a', 'b', 'c']

But should be: ['x', 'y', 'b', 'c']

How can I fix that?

Roger_88
  • 477
  • 8
  • 19
  • 1
    `for c in lsChars[:]:` – ComplicatedPhenomenon Aug 23 '19 at 00:55
  • when you remove item from list then it moves elements and then `for` can skip some of them. Better use `lsChars.count(c)` to see how many times remove it. OR create new list only with elements which you want to keep. – furas Aug 23 '19 at 00:56
  • `.remove()` has to traverse the whole list each time you call it. Creating a new one is more efficient, even if you assign it back to the variable: `lsChars = [c for c in lsChars if c != "a"]` (`lsChars[:] = …` to modify the actual list in place). Another efficient option is to loop backwards `for i in range(len(lsChars) - 1, -1, -1): if lsChars[i] == "a": del lsChars[i]` – Ry- Aug 23 '19 at 01:00
  • Use `lsChars = ['x', 'y', 'a', 'a', 'a', 'a', 'b', 'c'] for c in reversed(lsChars): if c == "a": lsChars.remove(c)` – Angelo Mendes Aug 23 '19 at 01:06
  • You can create a dictionary of the elements in the list (using `dict.fromkeys(lsChars)`) which will automatically remove the duplicate items. Then you can convert this dictionary back to list(Using `list()`).So you can write in one line like : `mylist=list(dict.fromkeys(lsChars))`. – Rohit Gawas Aug 23 '19 at 01:28
  • new = [ls for ls in lsChars if ls is not "a"] – Derek Eden Aug 23 '19 at 01:52

1 Answers1

-1

[ c for c in lsChars if c != 'a']

this works.

phimath
  • 1,322
  • 2
  • 12
  • 22