Skip to content
Advertisement

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?

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement