-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
  • 2,011
  • 4
  • 35
  • 62

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
  • 12,125
  • 9
  • 63
  • 94
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
  • 394
  • 4
  • 12