8

I have this function:

def foo():
    a = []
    if not a:
        print "empty"
        return None
    else:
        print "not empty"
        return a

Is there any Exception that do the same? Just to remove the if condition. Something like this:

def foo(list):
    try:
        a = list
        return a
    except:
        return None
ddepablo
  • 677
  • 1
  • 5
  • 16
  • Your first function doesn't make sense - `if not a:` will always be `True`...also, please don't use `list` as a variable name. – Tim Pietzcker Nov 16 '14 at 12:53
  • 2
    Also, why do you want to return `None` instead of an empty list? An empty list already evaluates to a boolean `False`, so what's the reasoning behind your question? – Tim Pietzcker Nov 16 '14 at 12:56
  • 2
    This sounds like the [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is it you actually want to do with the list? *Why* do you want to check if it's empty? – Lukas Graf Nov 16 '14 at 12:56

1 Answers1

11

I would just use return l if l else None, you could try to index the list but I would not recommend it.

def foo(l):
    try:
        l[0]
        return l
    except IndexError:
        return None
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321