0

I have scraped some data as strings and appended it into two separate lists.

I would like to delete an item (while item can be included several times) from a list called list_creatures_BP if it is present in another list called list_bosses_BP.

This is my code:

# append creatures to creatures list
for creatue in result_creatures_bp:
    list_creatures_BP.append(creatue.text)


# append bosses to bosses list
for boss in result_bosses_bp:
    list_bosses_BP.append(boss.text)


# delete bosses from creatures list
for item in list_creatures_BP:
    if item in list_bosses_BP:
        while item in list_creatures_BP:
            list_creatures_BP.remove(item)

But the item is still present in both lists.

What am I missing?

exec85
  • 447
  • 1
  • 5
  • 21

1 Answers1

3

I guess you mean:

newlist = []
for item in list_creatures_BP:
    if item not in list_bosses_BP:
        newlist.append(item)

Or just:

newlist = [item for item in list_creatures_BP if item not in list_bosses_BP]

The reason your code doesn't work is because:

  • You have an while loop with remove, remove behaves unexpectedly in loops, it will always right shift and it will modify the list incorrectly.
U13-Forward
  • 69,221
  • 14
  • 89
  • 114