Considering this code snippet:
from os import walk
files = []
for (dirpath, _, filenames) in walk(mydir):
# More code that modifies files
if len(files) == 0:
This was a issue in Pylint, and it no longer considers len(x) == 0
as incorrect.
You should not use a bare len(x)
as a condition. Comparing len(x)
against an explicit value, such as if len(x) == 0
of if len(x) > 0
is totally fine and not prohibited by PEP 8.
From PEP 8:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
Note that explicitly testing for the length is not prohibited. The Zen of Python states:
Explicit is better than implicit.
In the choice between if not seq
and if not len(seq)
, both are implicit, but the behaviour is different. But if len(seq) == 0
or if len(seq) > 0
are explicit comparisons and are in many contexts the correct behaviour.
In Pylint, PR 2815 has fixed this bug, first reported as issue 2684. It will continue to complain about if len(seq)
, but it will no longer complain about if len(seq) > 0
. The PR was merged 2019-03-19, so if you are using Pylint 2.4 (released 2019-09-14) you should not see this problem.