0

I am trying to work with the following code:

color= ['red' if House =="20" "blue" elif House =="21" "yellow" elif House =="22" else 'green' for H in House]

It gives the following error: SyntaxError: invalid syntax

Any suggestion-Idea?

Ze4
  • 125
  • 1
  • 1
  • 7

2 Answers2

1

elif can't be used in list comprehension. It should be else <value> if <condition>. Applying to your code:

color= ['red' if H=="20" else "blue" if H =="21" else "yellow" if H =="22" else 'green' for H in House]

Note you are iterating over H, not over House

update:

The general syntax look like:

[<value> if <condition> else <value> if <condition> else <value>]

This can be split into three parts:

  1. <value> if <condition>

    This corresponds to if <condition>: <value>

  2. else <value> if <condition>

    This corresponds to elif <condition>: <value>

  3. else <value>

    This corresponds to else: <value>

ViG
  • 1,848
  • 1
  • 11
  • 13
  • 1
    as you mention **else if ** up there but what you have done is **if else ** – Ayemun Hossain Ashik Feb 02 '20 at 07:05
  • @AyemunHossainAshik Before you can use an `elif` statement, you of course need an `if` statement. I've updated to answer to hopefully make it more clear. – ViG Feb 03 '20 at 18:39
  • I am talking about the line above you code . Correct that . – Ayemun Hossain Ashik Feb 04 '20 at 13:58
  • @AyemunHossainAshik I'm not sure I understand what you're trying to say. The line above the code says that if you want to use `elif` in list comprehension it should be written as `else if `. It is also like this is in the code as explained more in the update. – ViG Feb 05 '20 at 18:30
0

It would be easier to read if you use a dictionary:

colour_map = {
    '20': 'red',
    '21': 'blue',
    '22': 'yellow',
}

color= ['green' if H not in colour_map.keys() else colour_map[H] for H in House]
Dan
  • 45,079
  • 17
  • 88
  • 157