Getting the last element of a list

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

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

12条回答
  •  暖寄归人
    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.

提交回复
热议问题