0

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?

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Honestly, I think I would still prefer the if statement alternative. This feels like a little bit of mental gymnastics. Would refactor a little though if self.values is None: self.values = [] and then self.values.append(area)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.