In Python, how do you get the last element of a list?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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.Date: 2017-12-06
alist.pop()
I make an exhaustive cheatsheet of all list's 11 methods for your reference.
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.You can also use the code below, if you do not want to get IndexError when the list is empty.
if you want to just get the last value of list, you should use :
BUT if you want to get value and also remove it from list, you can use :
OR: you can pop with index too...
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. Sosome_list[-1]
gets the last element,some_list[-2]
gets the second to last, etc, all the way down tosome_list[-len(some_list)]
, which gives you the first element.You can also set list elements in this way. For instance:
Note that getting a list item by index will raise an
IndexError
if the expected item doesn't exist. This means thatsome_list[-1]
will raise an exception ifsome_list
is empty, because an empty list can't have a last element.