Python idiom to return first item or None

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:

def main():
    my_list = get_list()
    if len(my_list) > 0:
        return my_list[0]
    return None

but it seems to me that there should be a simple one-line idiom for doing this. Is there?

24 Answers
24

Leave a Comment