Empty Sequences Are Falsy
ID |
python.empty_sequences_false |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Python |
Tags |
best-practice, code-style |
Description
Reports comparisons of len(x) against a numeric literal that are equivalent to a truthy / falsy check on the sequence itself. Empty sequences are falsy in Python and non-empty sequences are truthy, so if len(items) == 0: should be written if not items:, len(items) > 0 should be items, and so on.
if len(items) == 0: # FLAW — use `if not items:`
...
if len(items) > 0: # FLAW — use `if items:`
...
if len(items) != 0: # FLAW — use `if items:`
...
if len(items) >= 1: # FLAW — use `if items:`
...
if not items: # OK
...
if items: # OK
...
Rationale
The shorter form is faster (no function call), reads more naturally for the cases the language was designed around, and is the PEP 8 recommendation. The longer len(…) == 0 form invites typos (⇐ 0, < 1) that drift from the intent.
Remediation
Replace len(x) == 0 with not x and len(x) > 0 (and friends) with x:
if not items:
return None
return items[0]
Keep len(…) when the actual length matters (len(items) == expected_count).