An empty list is itself considered false in true value testing (see python documentation):
a = []
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return True
else:
print('Structure is empty.')
return False
It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just is_empty(any_structure).
Readable and you don't have to worry about calling a function like len() to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless a was gigantic.
I have seen the below as preferred:
Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check
will also pass for
None
and other types of empty structures. If you truly want to check for an empty list, you can do this:An empty list is itself considered false in true value testing (see python documentation):
@Daren Thomas
Your duckCollection should implement
__nonzero__
or__len__
so the if a: will work without problems.From python3 onwards you can use
to check if the list is empty
EDIT : This works with python2.7 too..
I am not sure why there are so many complicated answers. It's pretty clear and straightforward
Simply use is_empty() or make function like:-
It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just
is_empty(any_structure)
.I prefer the following:
Readable and you don't have to worry about calling a function like
len()
to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unlessa
was gigantic.