Before getting to the main question, I should first ask: When you're trying to check if a list is empty in Python, is there any case where the four cases below would yield a different boolean?
if not []if not len([])if len([]) == 0if len([]) is 0If not, which is the fastest way to check for this boolean and why? - i.e. what exactly is happening under the hood for each case? The difference may be trivial but I'm curious as to how these might differ during execution.
if not array
This is the most idiomatic way to check it. Caveat: it will not work on other iterables, e.g. numpy arrays.
if not len(array)
Equivalent to the expression above, but is not as idiomatic. It will work on numpy arrays, but still might fail on other iterables with custom __len__ (nonexistent threat, to be clear)
if len(array) == 0
Same as above, but eliminates the nonexistent threat from custom iterables
if len(array) is 0
DANGER ZONE: it will work in CPython because of implementation details, but generally there is no guarantee it won't break in the future, or that it'll work on other Python implementations. Avoid at all costs.
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