Max Polokov
Max Polokov

Reputation: 41

Using Boolean instead of 'if' 'else'

I have a function that takes a list of numbers and returns the average. In order to handle a list of zero length, the function uses AND such that if the list is empty then the function returns 0, else returns the average

def avg(*args):
    count = len(args)
    total = sum(args)

    return count and total / count  

i dont understand why this works. If length is non zero, how does python know to return total/count?

Upvotes: 3

Views: 195

Answers (1)

Zenul_Abidin
Zenul_Abidin

Reputation: 839

Like jonrsharpe wrote, return count and total / count is equivalent to return total / count if count != 0 else count.

Why does it work?

The reason why they are equivalent is because the and operator evaluates the first statement, which here is count, and only if this expression is not false, it evaluates the statement on the right. So everything else will only see the value of the statement on the right.

But it's important to note that if the statement on the left is false, the value of the left statement is returned. So in 0 and total / count, 0 is returned. And in False and total / count, False is returned instead.

The expression can also be a function, which implies that in something like file.write('spam') and file.flush(), one of these functions might not be executed; if the file.write() call fails, and will not run the second expression and file.flush() won't be called, hence the file won't be flushed.

So, this expression could have drastic effects when writing to a database for example. It might not be clear to some people that an 'if' 'else' statement was the intention. In those cases, consider using an 'if' 'else' statement instead.

Upvotes: 1

Related Questions