-2

I am wondering how I would delete all items specified from a list, including all duplicates.

Here is a dumbed down version of my code, and it's only deleting half of the list each time. Wondering mostly why it doesn't delete all items at first.

blacklist = ['127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1', '127.0.0.1']
item = '127.0.0.1'

print(blacklist)
for _ in blacklist:
    blacklist.remove(item)
print(blacklist)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
nigel239
  • 1,485
  • 1
  • 3
  • 23
  • 1
    A quicker (and viable) way to do this would be `blacklist = [i for i in blacklist if i != item]`. – Samwise Mar 13 '22 at 20:16

1 Answers1

1
deduped = set(blacklist)
deduped.remove(item)

To remove multiple items

deduped = set(blacklist)

for item in items_to_remove:
    deduped.remove(item)
James Lin
  • 25,028
  • 36
  • 133
  • 233
  • And perhaps finally a `list(deduped)`. Might also change the order. – Luatic Mar 13 '22 at 20:11
  • He didn't specify the ordering in his question. – James Lin Mar 13 '22 at 20:11
  • Yeah, this works. Thanks. Just think it's weird why it's not deleting every item from the loop. – nigel239 Mar 13 '22 at 20:13
  • If a list contains duplicate elements, the remove() method only removes the first matching element. – James Lin Mar 13 '22 at 20:15
  • 1
    Also, see the linked dupe. Changing the length or ordering of the list while you're iterating screws up the iterator such that it no longer necessarily touches every element of the list. – Samwise Mar 13 '22 at 20:16
  • 1
    From the question, I see he only wanting to remove one item, but I will update my answer to include that – James Lin Mar 13 '22 at 20:18
  • Ahh, thank you Samwise, good to know! Sorry for not being specific enough in the question, James Linn, I'll think to be more specific in the future. – nigel239 Mar 13 '22 at 20:42