0

I have a simple list comprehension with "else 0" incorrectly placed at the end. I put that inside a try block, so I'm expecting the exception to be caught and the print statement to be executed. However, it's returning SyntaxError: invalid syntax. Here's the code:

try:
    [2 * x for x in [1,2,3] if x > 1 else 0]
except SyntaxError:
    print("Why isn't this printed?")

Why isn't the error being caught?

jss367
  • 4,759
  • 14
  • 54
  • 76

1 Answers1

0

Syntax Error Inconsistency

As @BrianMcCutchon mentions, if you are checking the syntax error inconsistency, please use eval for the same-

try:
    eval("[2 * x for x in [1,2,3] if x > 1 else 0]") #<----
except SyntaxError:
    print("Why isn't this printed?")
Why isn't this printed?

Syntax error in list comprehension

The error gets fixed if you fix the else in your list comprehension.

try:
    [2 * x  if x > 1 else 0 for x in [1,2,3]] #<----
except SyntaxError:
    print("Why isn't this printed?")

As @Ch3steR mentions in their comment as well, please refer to this post for more details.

#Returning element based on condition
[i for i in l if condition=True]

#Adding if else in list comprehension
[i if condition=True else j for i in l]
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51