Python idiom to return first item or None

后端 未结 24 1719
清酒与你
清酒与你 2020-12-07 07:46

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

相关标签:
24条回答
  • 2020-12-07 08:13

    Using the and-or trick:

    a = get_list()
    return a and a[0] or None
    0 讨论(0)
  • 2020-12-07 08:15

    my_list[0] if len(my_list) else None

    0 讨论(0)
  • 2020-12-07 08:16

    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]
    
    0 讨论(0)
  • 2020-12-07 08:16

    My use case was only to set the value of a local variable.

    Personally I found the try and except style cleaner to read

    items = [10, 20]
    try: first_item = items[0]
    except IndexError: first_item = None
    print first_item
    

    than slicing a list.

    items = [10, 20]
    first_item = (items[:1] or [None, ])[0]
    print first_item
    
    0 讨论(0)
  • 2020-12-07 08:17

    How about this:

    (my_list and my_list[0]) or None

    Note: This should work fine for lists of objects but it might return incorrect answer in case of number or string list per the comments below.

    0 讨论(0)
  • 2020-12-07 08:18

    Not sure how pythonic this is but until there is a first function in the library I include this in the source:

    first = lambda l, default=None: next(iter(l or []), default)
    

    It's just one line (conforms to black) and avoids dependencies.

    0 讨论(0)
提交回复
热议问题