Slava
Slava

Reputation: 425

conditional expression in one line if statment

self.values is optional parameter (List) in my class.

I have the following code:

self.values.append(area) if self.values else self.values = [area]

This produce

SyntaxError: can't assign to conditional expression

I know I can fix this by doing:

 if self.values:
    self.values.append(area)
 else:
    self.values = [area]

But isn't there a shorter way to set it?

Upvotes: 0

Views: 50

Answers (1)

azro
azro

Reputation: 54148

You can do the following, using the fact as it the list is None or empty, it's evaluated as false and the other operand of the OR expression will be used

self.values = (self.values or []) + [area]

Upvotes: 3

Related Questions