-4

I have a list: my_colors = ['blue', 'blue', 'blue', 'red', 'red', 'green']

And I have a 'valid' list: valid_colors = ['red', 'white', 'blue']

How can I remove any items in my list that are not in the valid list (valid_colors)? So that I get: my_colors = ['blue', 'blue', 'blue', 'red', 'red'] (no green)

NewToJS
  • 1,891
  • 4
  • 28
  • 54

2 Answers2

2

You can recreate my_colors using a list comprehension like so:

my_colors = [color for color in my_colors if color in valid_colors]
jmd_dk
  • 10,613
  • 6
  • 57
  • 84
0
my_colors = ['blue', 'blue', 'blue', 'red', 'red', 'green']
valid_colors = ['red', 'white', 'blue']

[v for v in my_colors if v in valid_colors]

['blue', 'blue', 'blue', 'red', 'red']

alexprice
  • 364
  • 4
  • 11