How to check if a List is empty in Python
Learn the easiest and most pythonic way to check if a List is empty in Python.
Learn the easiest and most pythonic way to check if a List is empty in Python.
Let's say we have an empty List:
my_list = []
#more
You can simply check if the List is empty with:
if not my_list:
print("List is empty")
This is using the Truth Value Testing in Python, also known as implicit booleaness or truthy/falsy value testing.
Among other rules it defines that empty sequences and collections like '', (), [], {}, set(), range(0)
are all considered false.
Another way which also works but is not necessary is to check if the length is equal to 0:
if len(my_list) == 0:
print("List is empty")
Although the first approach is considered to be more Pythonic, some people prefer the explicit second approach.
Note that the official PEP 8 Python Style Guide recommends the first way:
"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):
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*