python – How do I check if a list is empty?
python – How do I check if a list is empty?
if not a:
print(List is empty)
Using the implicit booleanness of the empty list
is quite pythonic.
The pythonic way to do it is from the PEP 8 style guide.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
python – How do I check if a list is empty?
I prefer it explicitly:
if len(li) == 0:
print(the list is empty)
This way its 100% clear that li
is a sequence (list) and we want to test its size. My problem with if not li: ...
is that it gives the false impression that li
is a boolean variable.