Categories
indexing list python

How do I get the last element of a list?

2605

How do I get the last element of a list?

0

    3776

    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.

    0

      307

      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.

      5

      • 39

        Downvoted because I feel the core of this answer is incorrect. Getting a list when you want an element only postpones the inevitable “list index out of range” – and that’s what should happen when attempting to get an element from an empty list. For Strings astr[-1:] could be a valid approach since it returns the same type as astr[-1], but I don’t think the ‘:’ helps to deal with empty lists (and the question is about lists). If the idea is to use “alist[-1:]” as a conditional instead of “len(alist) > 0”, I think it’s much more readable to use the later. (happy to upvote if I missed something)

        Jun 7, 2015 at 6:27

      • 10

        You’re down vote is understandable and valid. However I find there are two basic camps on what exception objects are intended for. One certainty is that exceptions halt your app. One camp uses exceptions in try clauses as the other camp would use the if len(alist)>0: structure instead. In any event, exceptions are objects that halt your code. And as such to me are less sequence object like then returned “null”-sequences which do not halt your code. My preference is to use IF clauses to test for “null” objects instead of objects that halt my code that I preempt with a try clause.

        – DevPlayer

        Jun 8, 2015 at 20:58

      • 6

        Upvoted because slice syntax is worth the discussion, however I agree with @StanKurdziel that the morphology is wrong, you’re just moving the goalpost – I found my own solution was related to the primary use of ‘add this to the list if you didn’t already add it’ (delta line graphs), so the combined expression if len(my_vector) == 0 or my_vector[-1] != update_val is a workable pattern. but it’s certainly not a global solution – it would be nice to have a syntax form where None was the result

        Mar 5, 2017 at 20:16

      • 25

        xs[-1] if xs else None

        – Gabriel

        Apr 28, 2018 at 2:35

      • 5

        Why would you “avoid” an IndexError? If you try to index an empty list or string, you’ll get an exception. If you want to handle that exception, use a try/except — that’s what it’s there for.

        Aug 1, 2018 at 2:18

      131

      You can also do:

      last_elem = alist.pop()
      

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

      1

      • 6

        NOTE: it’s worth knowing that this would also remove the last element from the list.

        Oct 28, 2021 at 18:22