1

I'm trying to assign a color to items from list if they are contained in another list. So far I'm using a list comprehension, and I get an error when I try to assign the color to those items which are not in a_list.

a_list = ['a', 'b', 'c', 'd', 'e', 'f']
b_list = ['b', 'f']

color = ['blue' for x in a_list if x in b_list else 'black']

ERROR MESSAGE:

File "<ipython-input-53-90957eb35bbb>", line 4
    color=['blue' for x in a_list if x in b_list else 'black']
                                                    ^
SyntaxError: invalid syntax
Red
  • 26,798
  • 7
  • 36
  • 58
Pablo
  • 167
  • 2
  • 9
  • 3
    In a list comprehension the `if` at the end is for *filtering*, you want a conditional expression as the *value*: `['blue' if x in b_list else 'black' for x in a_list]` – jonrsharpe Jan 08 '21 at 13:42

0 Answers0