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

首选哪种方式?

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

当前回答

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

next(reversed(some_list), None)

其他回答

您可以使用~运算符从end获取第i个元素(从0开始索引)。

lst=[1,3,5,7,9]
print(lst[~0])
array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

另一个简单的解决方案

您只需获取并放入[-1]索引即可。例如:

list=[0,1,2]
last_index=list[-1]
print(last_index)

您将得到2作为输出。

如果您使用负数,它将从列表的最后一个开始为您提供元素实例

lst=[1,3,5,7,9]
print(lst[-1])

后果

9

为了避免“IndexError:列表索引超出范围”,可以使用这段代码。

list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))