How to Get the Last Item in a List in Python



Python


In this article, we show how to get the last item in a list in Python.

There are really 2 ways, at least that I know of, of getting the last item of a list in Python.

The easiest way, by far, is getting the -1 index of a list.

So, say we have the following list in Python.



So we have a list of fruits.

We create a variable, lastitem, that gets the last item of this fruits list. This is done by inserting the -1 index in the fruits list.

We then reference the variable, lastitem, which gives us mango, as output.

So this is by far the easiest way to get the last item of a list in Python. All you have to do is retrieve the -1 index.

An alternative way of getting the last item in Python is to find the length of items in a list and then the last item will have an index of the length -1.

This is shown in the code below.



This is a little more complicated but still gets the job done and finds the last item in the list.

We have our list. We find the length of the list. Since the last item is always the length of the list - 1 (since the index begins at 0), we insert into the fruits list, fruits[len_items - 1].

So these are 2 ways you can get the last item in a list in Python.

Usually, you would want to go with the first method, but it's up to you.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...