[Tutor] Empty list validation

Kent Johnson kent37 at tds.net
Mon Jun 9 17:23:09 CEST 2008


On Mon, Jun 9, 2008 at 10:25 AM, qsqgeekyogdty at tiscali.co.uk
<qsqgeekyogdty at tiscali.co.uk> wrote:
> Hello
> Sorry if this is a basic question, but how do I check if list is empty
> or not and return True or False ;)

You can test the list directly, if it is empty it will evaluate to False:

if (myList):
  print 'Something in list'
else:
  print 'list is empty'

All containers (list, dict, set, string, etc) work this way:
"In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: False, None, numeric zero of all types, and empty strings
and containers (including strings, tuples, lists, dictionaries, sets
and frozensets). All other values are interpreted as true."
http://docs.python.org/ref/Booleans.html

If you really need a boolean value for some reason, use bool(myList).

Kent


More information about the Tutor mailing list