如何获取列表的最后一个元素?

首选哪种方式?

alist[-1]
alist[len(alist) - 1]

当前回答

您还可以执行以下操作:

last_elem = alist.pop()

这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。

其他回答

如果不想在列表为空时获取IndexError,也可以使用下面的代码。

next(reversed(some_list), None)

这是您查询的解决方案。

a=["first","second","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[1]) #prints second item in list 
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the second last item in the list.

输出:

>>> first
>>> second
>>> last
>>> second from last

Pythonic方式

因此,让我们考虑一下,我们有一个列表a=[1,2,3,4],在Python中,可以对列表进行操作,以将其一部分或其中的一个元素提供给我们,使用以下命令可以轻松获得最后一个元素。

print(a[-1])

要防止IndexError:list索引超出范围,请使用以下语法:

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'
array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

另一个简单的解决方案