I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
my_list = get_list()
if len(my_list) > 0: return my_list[0]
return None
It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?
Edit:
The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:
x = get_first_list()
if x:
# do something with x[0]
# inevitably forget the [0] part, and have a bug to fix
y = get_second_list()
if y:
# do something with y[0]
# inevitably forget the [0] part AGAIN, and have another bug to fix
What I'd like to be doing can certainly be accomplished with a function (and probably will be):
def first_item(list_or_none):
if list_or_none: return list_or_none[0]
x = first_item(get_first_list())
if x:
# do something with x
y = first_item(get_second_list())
if y:
# do something with y
I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function is the simple solution.
The most python idiomatic way is to use the next() on a iterator since list is iterable. just like what @J.F.Sebastian put in the comment on Dec 13, 2011.
next(iter(the_list), None)
This returns None ifthe_list
is empty. see next() Python 2.6+or if you know for sure
the_list
is not empty:iter(the_list).next()
see iterator.next() Python 2.2+Using the and-or trick:
Probably not the fastest solution, but nobody mentioned this option:
if
get_list()
can returnNone
you can use:Advantages:
-one line
-you just call
get_list()
once-easy to understand
The best way is this:
You could also do it in one line, but it's much harder for the programmer to read:
BTW: I'd rework your general program flow into something like this:
(Avoiding repetition whenever possible)
Several people have suggested doing something like this:
That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.