Python idiom to return first item or None

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

    Several people have suggested doing something like this:

    list = get_list()
    return list and list[0] or None
    

    That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.

    I've created this bug in my own code one too many times !

提交回复
热议问题