Python idiom to return first item or None

后端 未结 24 1977
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    2020-12-07 08:16

    My use case was only to set the value of a local variable.

    Personally I found the try and except style cleaner to read

    items = [10, 20]
    try: first_item = items[0]
    except IndexError: first_item = None
    print first_item
    

    than slicing a list.

    items = [10, 20]
    first_item = (items[:1] or [None, ])[0]
    print first_item
    

提交回复
热议问题