Getting the last element of a list in Python

2018-12-31 19:32发布

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

14条回答
旧时光的记忆
2楼-- · 2018-12-31 19:47

Ok, but what about common in almost every language way items[len(items) - 1]? This is IMO the easiest way to get last element, because it does not require anything pythonic knowledge.

查看更多
心情的温度
3楼-- · 2018-12-31 19:49

Date: 2017-12-06

alist.pop()

I make an exhaustive cheatsheet of all list's 11 methods for your reference.

{'list_methods': {'Add': {'extend', 'append', 'insert'},
                  'Entire': {'clear', 'copy'},
                  'Search': {'count', 'index'},
                  'Sort': {'reverse', 'sort'},
                  'Subtract': {'remove', 'pop'}}}
查看更多
泪湿衣
4楼-- · 2018-12-31 19:54

list[-1] will retrieve the last element of the list without changing the list. list.pop() will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.

Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1], assuming the list is not empty.

查看更多
永恒的永恒
5楼-- · 2018-12-31 19:55

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)
查看更多
骚的不知所云
6楼-- · 2018-12-31 19:57

if you want to just get the last value of list, you should use :

your_list[-1]

BUT if you want to get value and also remove it from list, you can use :

your_list.pop()

OR: you can pop with index too...

your_list.pop(-1)
查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 19:59

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

查看更多
登录 后发表回答