codeDigger
codeDigger

Reputation: 17

Python3: Syntax error when 'if' is used before the for loop

I'm getting a syntax error when if is used before the for loop without an else, but no such error when else is present.

Here is my code:

data=[[45, 12],[55,21],[19, -2],[104, 20]]
retData= ['Close' if i>54 and j>7 for [i,j] in data]
# getting a syntax error here :(
return retData

The code below works, which has if and else prior to the for loop.

data=[[45, 12],[55,21],[19, -2],[104, 20]]
retData= ['Close' if i>54 and j>7 else 'Open' for [i,j] in data]
# No Syntax error here!!
return retData

Upvotes: 0

Views: 65

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148900

Oups, there is a confusion between the Python syntax for the ternary operator:

expression_if_true if condition else expression_if_false

and the conditional list comprehension

[ expression for elt in list if condition ]

The second code is an unconditional list comprehension (no if after the for) where the expression contains a ternary operator.

In first code, you have no else condition, so you must use a conditional list comprehension, where the if acts on the for and is placed after if:

retData= ['Close' for [i,j] in data if i>54 and j>7]

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

The syntax you are looking for is.

data=[[45, 12],[55,21],[19, -2],[104, 20]]
retData= ['Close'  for [i,j] in data if i>54 and j>7]

if it is only if condition in list comprehension then it should come after the loop syntax.

Upvotes: 1

Related Questions