Reputation: 1539
I am following this:
if else in a list comprehension
but the following small program is generating a syntax error:
def to_rna(dnasequences):
xlate = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
return ''.join(xlate[sequence] for sequence in dnasequences if sequence in xlate.keys() else raise ValueError)
The else clause is generating the error.
If I remove the else clause it runs, however, I want to raise a ValueError for any input that is NOT a key in my dictionary 'xlate'.
NOTE I am working on the rna-transcription problem from exercism.io.
I pass 5 unit tests but I fail the three unit tests requiring a ValueError for invalid input.
Upvotes: 1
Views: 753
Reputation: 160467
You cannot do this in a comprehension. The conditional expression has the form:
expr if expr else expr
(and, sub-note, it should be used in the beginning of the comprehension)
while raise ExceptionClass
is a statement, not an expression. As such, a SyntaxError
is raised.
In short, if you do want to use raise
, you'll have to resort to a for
loop.
Alternately, if you're just very passionate about comprehensions, you could define a function which you can then call in the else
clause:
def raiser(exc_type):
raise exc_type
This is because function calls are expressions. Of course, this is quite ugly.
Upvotes: 4