I\'m a little curious about the difference between if and inline if, in Python. Which one is better?
Is there any reason to use inline if, other than the f
The correct way to use the conditional expression is:
result = X if C else Y
what you have is:
result = X if C else result = Y
So, you should remove the result =
part from there. The major advantage of conditional expression is that, it's an expression. You can use them wherever you would use a normal expression, as RHS of assignment expression, as method/function arguments, in lambdas, in list comprehension, so on. However, you can't just put any arbitrary statements in them, like say print
statements.
Fo e.g. suppose you want all even integers from a list, but for all odd numbers, you want the values as 0
. You would use it in list comprehension like this:
result = [x if x % 2 == 0 else 0 for x in li]