How to write Python if else in single line?

Question:

category.is_parent = True if self.request.get('parentKey') is not None else category.is_parent = False

Above is the code in which I am trying to write a if else in a single line and it is giving me this syntax error

SyntaxError: can't assign to conditional expression"

But if I write it in following way it works fine

if self.request.get('parentKey') is not None:
     category.is_parent = True
else:
    category.is_parent = False
Asked By: Saim Abdullah

||

Answers:

Try this:

category.is_parent = True if self.request.get('parentKey') else False

To check only against None:

category.is_parent = True if self.request.get('parentKey') is not None else False
Answered By: ettanany

You can write:

category.is_parent = True if self.request.get('parentKey') is not None else False

Or even simpler in this case:

category.is_parent = self.request.get('parentKey') is not None

Answered By: grepcake

You can write this with a one liner but using the [][] python conditional syntax. Like so:

category.is_parent = [False,True][self.request.get('parentKey') is not None

The first element in the first array is the result for the else part of the condition and the second element is the result when the condition in the second array evaluates to True.

Answered By: Kofi Nartey
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.