获取列表的最后一个元素

问题:获取列表的最后一个元素

在Python中,如何获取列表的最后一个元素?

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


回答 0

some_list[-1] 是最短和最Pythonic的。

实际上,您可以使用此语法做更多的事情。该some_list[-n]语法获取第n到最后一个元素。因此some_list[-1]获取最后一个元素,some_list[-2]获取倒数第二个,依此类推,一直向下到some_list[-len(some_list)],这将为您提供第一个元素。

您也可以通过这种方式设置列表元素。例如:

>>> 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]

请注意,IndexError如果期望的项目不存在,则按索引获取列表项将引发。这意味着some_list[-1]如果some_list为空将引发异常,因为空列表不能有最后一个元素。

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.


回答 1

如果您的str()list()对象最终可能是空的:astr = ''alist = [],那么您可能要使用alist[-1:]而不是alist[-1]对象“ sameness”。

其意义是:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

区别在于返回空列表对象或空str对象更像是“异常元素”,而不是异常对象。

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object “sameness”.

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more “last element”-like then an exception object.


回答 2

您也可以这样做:

alist.pop()

这取决于您要对列表执行的操作,因为该pop()方法将删除最后一个元素。

You can also do:

alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.


回答 3

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

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

还有许多其他方法可以实现这一目标,但是它们简短易用。

The simplest way to display last element in python is

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

there are many other method to achieve such a goal but these are short and sweet to use.


回答 4

在Python中,如何获取列表的最后一个元素?

为了获得最后一个元素,

  • 而不修改列表,以及
  • 假设您知道列表中最后一个元素(即非空)

传递-1给下标符号:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

说明

索引和切片可以采用负整数作为参数。

我已经从文档中修改了一个示例以指示每个索引引用序列中的哪个项目,在这种情况下,在string中"Python"-1引用最后一个元素(字符)'n'

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

通过迭代拆包分配

为了获取最后一个元素,但出于完整性的考虑,此方法可能不必要地实现第二个列表(并且由于它支持任何可迭代的对象-不只是列表):

>>> *head, last = a_list
>>> last
'three'

变量名head绑定到不必要的新创建的列表:

>>> head
['zero', 'one', 'two']

如果您不打算对该列表进行任何操作,则可能会更合适:

*_, last = a_list

或者,实际上,如果您知道它是一个列表(或至少接受下标符号):

last = a_list[-1]

在功能上

评论者说:

我希望Python像Lisp一样具有first()和last()函数…它将摆脱很多不必要的lambda函数。

这些定义起来非常简单:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

或使用operator.itemgetter

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

在任一情况下:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

特别案例

如果您正在做更复杂的事情,您可能会发现以略微不同的方式获取最后一个元素的性能更高。

如果您是编程的新手,则应避免使用本节,因为它会将原本在语义上不同的算法部分结合在一起。如果在某个地方更改算法,则可能会对另一行代码产生意外影响。

我尽力提供所有警告和条件,但我可能错过了一些东西。如果您认为我没有提出警告,请发表评论。

切片

列表的一部分将返回一个新列表-因此,如果要在新列表中使用该元素,我们可以从-1到末尾进行切片:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

如果列表为空,这样做的好处是不会失败:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

尝试通过索引访问会引发一个IndexError需要处理的问题:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

但是同样,仅在需要时才可以切片:

  • 创建一个新列表
  • 如果先前列表为空,则新列表为空。

for 循环

作为Python的功能,for循环中没有内部作用域。

如果您已经对列表执行了完整的迭代,则最后一个元素仍将由循环中分配的变量名称引用:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

从语义上讲,这并不是列表中的最后一件事。从语义上讲,这是名称item绑定到的最后一件事。

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

因此,只有当您

  • 已经在循环,并且
  • 您知道循环将结束(不会由于错误而中断或退出),否则它将指向循环引用的最后一个元素。

获取和删除它

我们还可以通过删除并返回最后一个元素来更改原始列表:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

但是现在原始列表已修改。

-1实际上是默认参数,因此list.pop可以在没有索引参数的情况下使用):

>>> a_list.pop()
'two'

仅在以下情况下这样做

  • 您知道列表中有元素,或者准备为空时处理异常,并且
  • 您确实打算从列表中删除最后一个元素,将其视为堆栈。

这些是有效的用例,但不是很常见。

保存相反的其余部分以供以后使用:

我不知道为什么要这么做,但出于完整性考虑,由于reversed返回了迭代器(支持迭代器协议),您可以将其结果传递给next

>>> next(reversed([1,2,3]))
3

所以就像做相反的事情:

>>> next(iter([1,2,3]))
1

但是我想不出这样做的充分理由,除非稍后需要其余的反向迭代器,这可能看起来像这样:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

现在:

>>> use_later
[2, 1]
>>> last_element
3

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

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable – not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it’s a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does… it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you’re doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you’re new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I’m leaving a caveat out.

Slicing

A slice of a list returns a new list – so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you’re performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don’t know why you’d do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it’s like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can’t think of a good reason to do this, unless you’ll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3

回答 5

为了防止IndexError: list index out of range,请使用以下语法:

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'

To prevent IndexError: list index out of range, use this syntax:

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'

回答 6

另一种方法:

some_list.reverse() 
some_list[0]

Another method:

some_list.reverse() 
some_list[0]

回答 7

lst[-1]是最好的方法,但是对于一般的可迭代对象,请考虑more_itertools.last

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

lst[-1] is the best approach, but with general iterables, consider more_itertools.last:

Code

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

回答 8

list[-1]将检索列表的最后一个元素而不更改列表。 list.pop()将检索列表的最后一个元素,但它将更改/更改原始列表。通常,不建议更改原始列表。

另外,如果出于某种原因,您正在寻找一些不符合pythonic的工具,则可以使用list[len(list)-1],假设列表不为空。

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.


回答 9

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

next(reversed(some_list), None)

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)

回答 10

好的,但是几乎每种语言都常见items[len(items) - 1]吗?这是IMO获得最后一个元素的最简单方法,因为它不需要任何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.