For example, if passed the following:
a = []
How do I check to see if a
is empty?
For example, if passed the following:
a = []
How do I check to see if a
is empty?
if not a:
print "List is empty"
Using the implicit booleanness of the empty list is quite pythonic.
I have seen the below as preferred, as it will catch the null list as well:
if not a:
print "The list is empty or null"
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.
I prefer the following:
if a == []:
print "The list is empty."
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.
The pythonic way to do it is from the style guide:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes:
if not seq:
if seq:
No:
if len(seq)
if not len(seq)
len() is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.
JavaScript has a similar notion of truthy/falsy.
It's silly to compare if a==[] because as mentioned, it breaks polymorphism, worse, extra object creation, a sin, even if it's very fast. len IS the preferred way, because it's standard and any inherited class should support it.