How to get the last element of a list in Python

1 min read 230 words

Let’s say that you have a Python list with the following 5 foods:

foods = ["pizza", "pasta", "steak", "chicken", "olives"]

How do we go about getting the last item?

Option 1

It’s actually really easy, you can select the index item by it’s total length minus one.

last_item = foods[len(foods)-1]

# "olives"

Option 2

Python has some really fantastic functionality around making your life easier. One of those such things is the ability to use slices.

You can return an item by it’s index if you know this, or you can return it’s value from the place within a list.

last_item = foods[-1]

# "olives

By stipulating an index of -1, we tell Python to return the last item; we can also return the second last item by using the index -2. This indexing technique is one of the many powerful features that make Python great for array operations like finding the intersection of two arrays .

Additional safety checking

As with option2 above, this is a nice and simple way to achieve our objective, but what if the str() or list() object is empty? Understanding these edge cases is important when learning Python programming .

List example

alist = []

# Generates an IndexError exception
alist[-1]
# Return an empty list
alist[-1:]

String example

astr = ''

# Generate an IndexError exception
astr[-1]
# Return an empty string
astr[-1:]
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags