Monday, February 7, 2011

Python: What is the best way to check if a list 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.

    Frep D-Oronge : up'd for 'pythonic'
    From Patrick
  • 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"
    
    Vinko Vrsalovic : There is no null list in Python, at most a name bound to a None value
    From hazzen
  • 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.

    Chris Lutz : 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.
  • 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.

    Daren Thomas : Yes, but it does break polymorphism...
    Konrad Rudolph : Big-O-notation is completely irrelevant here. The input is an *empty* list, meaning that the n in O(n) equals zero.
    Carl Meyer : Big O notation aside, this is going to be slower, as you instantiate an extra empty list unnecessarily.
    From verix
  • 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)
    
    Carl Meyer : up'd for linking the style guide as an authoritative reference
    Patrick Johnmeyer : 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.
    From Harley
  • 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.

0 comments:

Post a Comment