I want to check if an item is in a list and if not, I want to append it to the list.
Usually I would write it:
if item not in list:
list.append(item)
else:
pass
However, I got to the point where I try to keep my code shorter and got to this:
list.append(item) if item not in list else list
To be fair, only list.append(item) if item not in list is my own creation. The else statement is due to insistence of PyCharm. Now to my question: Why can't I follow up the else statement with pass but must write list instead. I can't wrap my head around it, nor did Google help too.
Thanks for your clarifications.
There is a difference between an if statement and a conditional expression.
When you write
if condition:
this()
else:
that()
you are writing a statement. It is an imperative construct — it does something. And the else bit is optional; if it is omitted, the statement will do nothing if the condition is not fulfilled.
The this if condition else that construct is an expression. It computes a value. It always has to compute a value, so the else bit has to be there. Using it for its side effects, for example by calling `list.append(), which doesn't return anything useful, is... not exactly wrong, but... well, it is wrong. Not technically, but philosophically.
So, when you want to compute a value, in one of two possible ways, and the whole thing fits in a line or so, use a conditional expression. If you want to do either of two things, one of which may be nothing, use an if statement.
Notice that you write
if temperature < 0:
coat = thick
else:
coat = thin
but
coat = thick if temperature < 0 else thin
In the first case, you have an if statement that selects which of two assignment statements to execute. In the second case, you have a single assignment statement, which uses a conditional expression to decide which value to assign.
Expressions can be used as statements (in which case their value is simply ignored), but statements have no value, and thus cannot be used as expressions.
In your first snippet, the else statement is redundant, i.e.
if item not in a_list:
list.append(item)
is enough and is as short and idiomatic as it can get (you might want to try sets for performance though).
In the second snippet, you're using a conditional expression to append to a list, which is not what those expressions are for. A conditional expression must have a value regardless of the condition, and pass is not a value. Use the conditional statements like above unless you need to compute a value based on the condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With