Getting the last element of a list

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

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

相关标签:
12条回答
  • 2020-11-22 05:58

    To prevent IndexError: list index out of range, use this syntax:

    mylist = [1, 2, 3, 4]
    
    # With None as default value:
    value = mylist and mylist[-1]
    
    # With specified default value (option 1):
    value = mylist and mylist[-1] or 'default'
    
    # With specified default value (option 2):
    value = mylist[-1] if mylist else 'default'
    
    0 讨论(0)
  • 2020-11-22 05:59

    You can also use the code below, if you do not want to get IndexError when the list is empty.

    next(reversed(some_list), None)
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-22 06:04

    You can also do:

    alist.pop()
    

    It depends on what you want to do with your list because the pop() method will delete the last element.

    0 讨论(0)
  • 2020-11-22 06:04

    Another method:

    some_list.reverse() 
    some_list[0]
    
    0 讨论(0)
  • 2020-11-22 06:05

    If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

    The significance of this is:

    alist = []
    alist[-1]   # will generate an IndexError exception whereas 
    alist[-1:]  # will return an empty list
    astr = ''
    astr[-1]    # will generate an IndexError exception whereas
    astr[-1:]   # will return an empty str
    

    Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

    0 讨论(0)
提交回复
热议问题