Get the last element of a Python list

Read a list’s final item with negative indexing, handle empty lists deliberately, and distinguish reading an item from removing it.

Best practices
Python programming and application logging

Use items[-1] to read the last element. Negative indexes count backward from the end, so -2 refers to the second-to-last element.

items = [1, 2, 3, 4, 5]
print(items[-1])  # 5

The same indexing convention applies to tuples and strings. An empty list has no final item, so items[-1] raises IndexError when items is empty.

Handle an empty list

If your application has a suitable default:

items = []
last = items[-1] if items else None
print(last)  # None

Choose a separate sentinel when None can itself be a meaningful item. Alternatively, retain a list-shaped result with a slice:

print([1, 2, 3][-1:])  # [3]
print([][-1:])         # []

A slice returns a list containing zero or one element, not the element itself. That difference matters to callers.

Avoid calculating the final index yourself

items[len(items) - 1] works for a nonempty list, but says less directly what you want. It has the same empty-list problem as items[-1].

FAQ

Can I replace the last item? Yes: items[-1] = 99 modifies a nonempty list in place. Reading it does not remove it; items.pop() removes and returns it.

How do I get the last N items? For a positive n, use items[-n:]. If there are fewer than n elements, the whole list is returned. Handle zero explicitly, because items[-0:] means items[0:] and returns everything:

def tail(items, n):
    if n < 0:
        raise ValueError("n must be nonnegative")
    return items[-n:] if n else []

Does deque support this? collections.deque supports d[-1] for reading its final item. Its pop() and popleft() remove items from opposite ends. Unlike lists, deques do not support ordinary slicing.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting