views:

27447

answers:

7

For example, if passed the following:

a = []

How do I check to see if a is empty?

+96  A: 
if not a:
  print "List is empty"

Using the implicit booleanness of the empty list is quite pythonic.

Patrick
up'd for 'pythonic'
Frep D-Oronge
+1  A: 

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"
hazzen
There is no null list in Python, at most a name bound to a None value
Vinko Vrsalovic
+3  A: 

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.

Peter Hoffmann
You can use backticks to format `code blocks` inside regular text. Do that instead of making it look worse to avoid the other formatting StackOverflow has.
Chris Lutz
A: 

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.

verix
Yes, but it does break polymorphism...
Daren Thomas
Big-O-notation is completely irrelevant here. The input is an *empty* list, meaning that the n in O(n) equals zero.
Konrad Rudolph
Big O notation aside, this is going to be slower, as you instantiate an extra empty list unnecessarily.
Carl Meyer
+42  A: 

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)
Harley
up'd for linking the style guide as an authoritative reference
Carl Meyer
Note that if seq is None you will get the same response as if seq is an empty list; if logic needs to be different in this case you need to explicitly check for None separately.
Patrick Johnmeyer
+2  A: 

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.

George V. Reilly
A: 

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.

Daniel Goldberg