Examples of how to check if a list is empty in python:
Check if a list is empty in python (solution 1)
To ckeck if a list is empty in python, a simple solution is to use a logical expression:
mylist = []
then
not mylist
returns
True
because the list is empty.
Another example
mylist = [4,2,7]
then
not mylist
returns
False
because the list is not empty.
Can then be used with a if condition:
if not mylist:
print("List is empty")
else:
print("list is not empty")
Check if a list is empty in python (solution 2)
Another solution is to use len. If the list lenght returns 0 then the list is empty
mylist = []
then
len(mylist)
returns
0
Example
mylist = []
if len(mylist) == 0:
print 'List is empty'
References
- Best way to check if a list is empty | stack overflow
- Get the size of a list in python? | stack overflow
- Built-in Functions | Python Doc