python - Comment obtenir le dernier élément d'une liste

Mots clés : pythonlistindexingpython

meilleur 5 Réponses python - Comment obtenir le dernier élément d'une liste

vote vote

90

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

90

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

78

last_elem = alist.pop() 
vote vote

63

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

50

>>> a_list = ['zero', 'one', 'two', 'three'] >>> a_list[-1] 'three' 
 +---+---+---+---+---+---+  | 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 ['zero', 'one', 'two'] 
*_, last = a_list 
last = a_list[-1] 
def last(a_list):     return a_list[-1]  def first(a_list):     return a_list[0] 
>>> import operator >>> last = operator.itemgetter(-1) >>> first = operator.itemgetter(0) 
>>> last(a_list) 'three' >>> first(a_list) 'zero' 
>>> a_slice = a_list[-1:] >>> a_slice ['three'] 
>>> empty_list = [] >>> tail = empty_list[-1:] >>> if tail: ...     do_something(tail) 
>>> empty_list[-1] Traceback (most recent call last):   File "<stdin>", line 1, in <module> IndexError: list index out of range 
>>> def do_something(arg): pass >>> for item in a_list: ...     do_something(item) ...      >>> item 'three' 
>>> 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'] 
>>> a_list.pop() 'two' 
>>> 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 

Questions similaires