len
used as condition PYL-C1802len(SEQUENCE)
without comparison to determine if a sequence is empty 42 def __setitem__(self, key, value):
43 with timer('write %s' % key):
44 if isinstance(value, pandas.core.frame.DataFrame):
45 if len(value): 46 for c in value.columns:
47 first = value[c].iloc[0]
48 if isinstance(first, datetime) and \
Using the len
function to check if a sequence is empty is not idiomatic and can be less performant than checking the truthiness of the object.
len
doesn't know the context in which it is called, so if computing the length means traversing the entire sequence, it must; it doesn't know that the result is just being compared to 0.
Computing the boolean value can stop after it sees the first element, regardless of how long the sequence actually is.
Not preferred:
if not len(my_sequence):
print("Empty sequence.")
else:
print("Sequence is not empty.")
Preferred:
if not my_sequence:
print("Empty sequence.")
else:
print("Sequence is not empty.")