Python idiom to return first item or None

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

    Frankly speaking, I do not think there is a better idiom: your is clear and terse - no need for anything "better". Maybe, but this is really a matter of taste, you could change if len(list) > 0: with if list: - an empty list will always evaluate to False.

    On a related note, Python is not Perl (no pun intended!), you do not have to get the coolest code possible.
    Actually, the worst code I have seen in Python, was also very cool :-) and completely unmaintainable.

    By the way, most of the solution I have seen here do not take into consideration when list[0] evaluates to False (e.g. empty string, or zero) - in this case, they all return None and not the correct element.

提交回复
热议问题