Python idiom to return first item or None Python idiom to return first item or None python python

Python idiom to return first item or None

Python 2.6+

next(iter(your_list), None)

If your_list can be None:

next(iter(your_list or []), None)

Python 2.4

def get_first(iterable, default=None):    if iterable:        for item in iterable:            return item    return default


x = get_first(get_first_list())if x:    ...y = get_first(get_second_list())if y:    ...

Another option is to inline the above function:

for x in get_first_list() or []:    # process x    break # process at most one itemfor y in get_second_list() or []:    # process y    break

To avoid break you could write:

for x in yield_first(get_first_list()):    x # process xfor y in yield_first(get_second_list()):    y # process y


def yield_first(iterable):    for item in iterable or []:        yield item        return

The best way is this:

a = get_list()return a[0] if a else None

You could also do it in one line, but it's much harder for the programmer to read:

return (get_list()[:1] or [None])[0]

(get_list() or [None])[0]

That should work.

BTW I didn't use the variable list, because that overwrites the builtin list() function.

Edit: I had a slightly simpler, but wrong version here earlier.