Note that there are some explanatory texts on larger screens.

plurals
  1. POPython idiom to return first item or None
    text
    copied!<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>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:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>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?</p> <p><strong>Edit:</strong></p> <p>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:</p> <pre><code>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 </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>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 </code></pre> <p>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 <em>is</em> the simple solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload