Python idiom to get first item in an object if object is a list. Otherwise the object

Viewed 30

When you have a Python3 object and know that the object is either the non-list object you need or it is a list whose first item is the object you need, is there a good idiom for getting the object you need?

Essentially I'm looking for an inline alternative to:

def first_or_whole(item):
    if isinstance(item, list):
        return item[0]
    return item

# Elsewhere
thing_i_need = first_or_whole(is_either_a_list_with_thing_i_need_at_head_or_else_is_the_thing_i_need)
0 Answers
Related