Sal
Peter Hoffmann Director Data Engineering at Blue Yonder. Python Developer, Conference Speaker, Mountaineer

Python What is the best way to check if a list is empty?

This my Answer to the stackoverflow question: Python: What is the best way to check if a list is empty?:

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.