Imagine a list that has random words:
words = ['elephant', 'dog', 'blue', 'sam', 'white', 'red', 'sun', 'moon']
And I want to remove all but the following words (like a whitelist):
colors = ['red', 'green', 'blue', 'orange', 'white']
And I want to produce the following list (order matters):
filtered = ['blue', 'white', 'red']
I’ve thought about something like this (which works fine):
filtered = filter (lambda a: a == 'red' or a == 'green' or a == 'blue' or a == 'orange' or a == 'white', words)
But is this really the best / most efficient way?
If you want to keep order and efficiently filter out non-colors, create a
setof colors, so thatinchecking is faster and then you can just go thru all words and filter out non-colorsoutput: