Home > front end >  Is it pythonic to assign a variable with if else statement?
Is it pythonic to assign a variable with if else statement?

Time:10-18

I was wondering if it is professional to assign a variable like this:

for i in range(m):
    incorrect  = 1 if yhat[i]!=y[i] else 0

CodePudding user response:

Like it's been pointed out, statements like this are 100% Pythonic

a = FIRST_VALUE if CONDITION else OTHER_VALUE

The problem with your code is that it's not clear from the first glance what's happening when yhat[i] == y[i]:

  • incorrect = 0
  • or
  • incorrect = 0?

Therefore I think your snippet in not Pythonic.

This is how I would have written that:

sum(x != y for x, y in zip(y, yhat))

CodePudding user response:

Yes, it is.

conditional_expression ::= or_test ["if" or_test "else" expression] The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

Here you can find some more details.

CodePudding user response:

It depends. It's certainly valid. Opinions will differ. I rather like the extension of what you have done to ...

incorrect = sum(map(lambda i: 1 if yhat[i] != y[i] else 0, range(m)))

ETA: @kaya's even better version.

incorrect = sum([yhat[i] != y[i] for i in range(m)])

After all, if you are going for the most concise version, nothing beats a one-liner.

Except for the zen of python which I feel the one-liner breaks.

I normally avoid in-line if then else expressions in python because they don't really feel like they are in the spirit of the language.

ETA: For a laugh I ran this through the flake8 linter ... and it passed :D. I've come to view the linter output as the most pragmatic means of reducing arguments of opinion, and for coding style these are never out of fashion.

  • Related