Python check list is empty
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Another way to do it:
This way it's 100% clear that
li
is a sequence (list) and we want to test its size. My problem withif not li: ...
is that it gives the false impression thatli
is a boolean variable.
That does make some sense, but following PEP 8 style, it is ugly and unpythonic. If distinguishing list from boolean is important, you should add a comment, not more codes.
Last updated