Getting the last element of a list

后端 未结 12 1481
一向
一向 2020-11-22 04:58

In Python, how do you get the last element of a list?

12条回答
  •  清歌不尽
    2020-11-22 06:03

    lst[-1] is the best approach, but with general iterables, consider more_itertools.last:

    Code

    import more_itertools as mit
    
    
    mit.last([0, 1, 2, 3])
    # 3
    
    mit.last(iter([1, 2, 3]))
    # 3
    
    mit.last([], "some default")
    # 'some default'
    

提交回复
热议问题