Python idiom to return first item or None

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

提交回复
热议问题