Python idiom to return first item or None

后端 未结 24 2056
清酒与你
清酒与你 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: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]
    

提交回复
热议问题