0

I have a list of animals:

list_animals = ['dog', 'cat', 'cow', 'tiger', 'lion', 'snake', 'lion']

and a set of pets:

set_pets = set(['dog', 'cat'])

I want to remove pets in set_pets from list_animals but still keep the original orders of list_animals. Would this be possible?

I tried to do: set(list_animals) - set_pets, but then it doesn't keep the original animal orders ...

Thanks!

JGFMK
  • 8,425
  • 4
  • 58
  • 92
Edamame
  • 23,718
  • 73
  • 186
  • 320

2 Answers2

1

You can do this easily with a list comprehension:

result = [a for a in list_animals if a not in set_pets]
['cow', 'tiger', 'lion', 'snake', 'lion']

I had a second method in here that uses list.remove(), but it was inefficient. List comp is the way to go.

Engineero
  • 12,340
  • 5
  • 53
  • 75
  • 3
    This is very inefficient compared to list comp. – pault Jul 24 '18 at 21:36
  • 1
    Honestly, I wouldn't even keep the for loop in this answer- `list.remove()` is going to search through (potentially) all the items in `list_animals` every time you call it. – Ben Jones Jul 24 '18 at 21:43
  • Good point, although he did specifically say he wants to *remove* all of the pets, so I guess I had `list.remove()` in my brain :P – Engineero Jul 24 '18 at 21:44
1
list_animals = ['dog', 'cat', 'cow', 'tiger', 'lion', 'snake', 'lion']
set_pets = set(['dog', 'cat'])
list_animals = list(filter(lambda x: x not in set_pets, list_animals))
print(list_animals)

Outputs

['cow', 'tiger', 'lion', 'snake', 'lion']  
JGFMK
  • 8,425
  • 4
  • 58
  • 92