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 <=:
- The actual condition that I want to check is
not len(my_list) > 0which is equivalent tolen(my_list) <= 0, so that is correct for sure. - As explained in point 1,
len(my_list) == 0alone 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 thelen()implementation performs some validations on the value. One could argue thatlen()implementation may change in the future, so the equivalence would not hold anymore. - I feel
len(my_list) <= 0would be safer in general than usinglen(my_list) == 0plus 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.