Python

Python

Made by DeepSource

Built-in function len used as condition PYL-C1802

Performance
Major
Autofix

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.")