Python idiom to return first item or None

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

提交回复
热议问题