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

首选哪种方式?

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

当前回答

这是您查询的解决方案。

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

其他回答

另一种方法:

some_list.reverse() 
some_list[0]

在python中显示最后一个元素的最简单方法是

>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。

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

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

您将得到2作为输出。

这是您查询的解决方案。

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

奇怪的是还没有人发布这个:

>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>> 

打开包装。