Reputation: 711
I have been part of a code review in which I have a condition such as this one (Python code):
my_list = <whatever list>
if len(my_list) <= 0:
do_something()
I have been pointed out that the condition should be ==
instead of <=
as a list cannot have a negative length. I have no issues with it in this case, but I wanted to know if there is really any drawbacks on using <=
.
Here is my rationale on why to use <=
:
not len(my_list) > 0
which is equivalent to len(my_list) <= 0
, so that is correct for sure.len(my_list) == 0
alone is not equivalent to the original condition. It is in this case, but it is not trivial why it is this way. len()
returns the value returned by __len__()
which may be an arbitrary. It only happens to be equivalent because the len()
implementation performs some validations on the value. One could argue that len()
implementation may change in the future, so the equivalence would not hold anymore.len(my_list) <= 0
would be safer in general than using len(my_list) == 0
plus an assumption that might not hold in some edge or unexpected cases.So, are my arguments correct? Do you know any drawbacks of using len(my_list) <= 0
?
Sorry if this seems like a non-relevant question, but this have been raised to me more than once on code reviews so wanted to understand if there is something I am missing.
Upvotes: 5
Views: 88
Reputation: 1166
So, after some more digging I found this in the python PEP 8 programming recommendations (https://peps.python.org/pep-0008/#programming-recommendations)
# Not recommended
my_list = []
if not len(my_list):
print('List is empty!')
# Recommended
my_list = []
if not my_list:
print('List is empty!')
so now you know the most pythonic way to check if a list is empty!
After testing a bit, I found this works even for custom classes! But my test might be incomplete.
class Test:
def __init__(self, len):
self.len = len
def __len__(self):
return self.len
t1 = Test(3)
if len(t1):
print("len1 > 0")
if t1:
print("len2 > 0")
t1 = Test(0)
if len(t1):
print("len3 > 0")
if t1:
print("len4 > 0")
t1 = Test(-1)
if len(t1):
print("len5 > 0")
prints
len1 > 0
len2 > 0
Exception has occurred: ValueError
__len__() should return >= 0
Upvotes: 1