What are the benefits of writing:
def contains(lst, n):
for x in lst:
if x == n:
return True
return False
instead of:
def contains(lst, n):
for x in lst:
if x == n:
return True
?
Please note that in the second example the last line of code is missing, and the function returns None
instead of False
.
Side note: I'm aware I should write n in lst
, this is just an example.
I think to some extent this is a matter of personal preference.
I personally would always prefer former over the latter, since "explicit is better than implicit".
Also, if the function is expected to return a bool
, I think it's cleaner to return a bool
and not some other object whose truthiness needs to be evaluated in order to get a bool
.
It really depends on how you intend the function to be used.
If it's only ever going to be used in a boolean context, it might make sense to define and document it as "returns something truthy or something falsey", in which case it's reasonable to return None
as something falsey.
But if you expect people to, say, log the result for human debugging purposes, or use it as a key in a dictionary—or you just don't know how it's going to be used—it's a lot clearer to say it returns a boolean and then explicitly return False
.
In fact, it's often a nice idea to be stricter than you promise in what you provide; even if you only document that you're returning something truthy or falsey, it won't actually hurt to always return True
or False
, unless you have some other value that could be meaningful.* As the other answers imply, this doesn't just go along with general programming principles, but also the specific Python Zen "explicit is better than implicit".
* If you're thinking that it could hurt performance, it won't, even if that were an issue. An implicit return None
complies to exactly the same LOAD_CONST
and RETURN_VALUE
as an explicit return None
—or, of course, an explicit return False
.
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