Python empty list Exception [closed]
Asked Answered
I

1

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
Instalment answered 16/11, 2014 at 12:47 Comment(3)
Your first function doesn't make sense - if not a: will always be True...also, please don't use list as a variable name.Tass
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?Tass
This sounds like the XY problem. What is it you actually want to do with the list? Why do you want to check if it's empty?Matt
D
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
Discountenance answered 16/11, 2014 at 12:53 Comment(2)
It is better to not use just except, as it can hide unexpected errors. Use except IndexError instead.Damaraland
@stalk, true, added, I would not use an except at all, it was just to show that it was possible.Discountenance

© 2022 - 2024 — McMap. All rights reserved.