How To Get the Last Item in a List in Python

Use slice notation and learn to safeguard your application

Jonathan Hsu
Nov 27, 2019 · 3 min read
Photo by Jessica Lewis on Unsplash

In Python, a list is an ordered, mutable container of values. If that sounds too heavy, it’s analogous to an array in other programming languages.

Retrieving the last item in a list is a relatively simple task, but an excellent exercise for demonstrating some core Python concepts. We’ll be going over the following in this tutorial:

  • What are iterables and indexes?
  • What is slice notation?
  • What is an IndexError?

If you don’t want to read on, use -1 as the index to get the last item in the array. For everybody else, enjoy the explanation!

What Are Iterables and Indexes?

In its simplest terms, an iterable is a value that can be iterated over. Tracing the root of the word iterate, an iterable can have the same value performed for each individual element.

Lists are an iterable, with each item being the individual element. Strings are iterables as well, with each character being the individual element.

Indexes — or indices — are used to keep track of your position within an iterable. An index is a whole number starting at 0. Here are examples of printing the second element in a list as well as a string.

numbers = [100,200,300,400]
name = "Jonathan"
print(numbers[1]) # 200
print(name[1]) # o

What Is Slice Notation?

If you’ve seen Python iterables with complicated indexes that include colons, you’re probably looking at slice notation.

The slice() function — in actuality a constructor that returns a slice object — is used to create a subset from a given iterable. Slice notation is a shorthand technique for performing a slice. The notation is written within the square brackets of an iterable and has the following syntax [start,stop,step].

Here are a few simple examples for you to get familiar (the first is the answer to the article’s topic):

numbers = [100,200,300,400]# start at index 1, step forward one at a time
print(numbers[1:]) # [200, 300, 400]
# start at index 0, step forward one at a time and stop at index 2
print(numbers[0:2]) # [100, 200]
# step backwards every two items
print(numbers[::-2]) # [400, 200]
# step backwards one at a time and end at index 1
print(numbers[:1:-1]) # [400, 300]
# step backwards one at a time
print(numbers[::-1]) # [400, 300, 200, 100]

As you can see, each of the three positions are optional and allow you to nimbly traverse subsections of an iterable.

What Is an IndexError?

If you know that your iterable will not be empty with absolute certainty, then this won’t be an issue. But—and this is a huge but—if there is any chance that your iterable will be empty then you need to plan accordingly for the possibility of an IndexError.

An IndexError is the exception that is thrown when an index that does not exist is attempted to be accessed.

scores = []print(scores[-1]) # IndexError: list index out of range

If not planned for, the IndexError will halt your application.

To remedy this, use a try/except statement to gracefully handle the exception.

scores = []try:
except IndexError:
print("Index does not exist")

With try/except statements, you can add multiple exceptions and customize how each one is handled.

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade