Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python empty list Exception [closed]

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
like image 311
ddepablo Avatar asked Nov 16 '14 12:11

ddepablo


1 Answers

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
like image 110
Padraic Cunningham Avatar answered Sep 21 '22 02:09

Padraic Cunningham