Explain Codes LogoExplain Codes Logo

How to get last items of a list in Python?

python
slice
negative-indexing
iterables
Alex KataevbyAlex Kataev·Aug 29, 2024
TLDR

To fetch the last N elements in a list, slice it using [-N:].

items = ['a', 'b', 'c', 'd'] print(items[-2:]) # Output: ['c', 'd']

The slice gets the Nth item from the end up to the last item.

Slice and dice like a Python pro

  • Negative indexing
    • To put it simply, Python has a 'go back home' shortcut - a negative index.
reversed_items = items[::-1] print(reversed_items[:2]) # Output: ['d', 'c']
  • Not just reversing a list, it's like walking home backwards. You reach home but with a twist!

  • Slice objects

last_two_slice = slice(-2, None) print(items[last_two_slice]) # Output: ['c', 'd']
  • They are like placeholders but with swords - slicing wherever they go.

Utilize external libraries and itertools

Non-list iterables can be pretty elusive guys. They won't let you use negative indexing. So, enter itertools.islice, it's almost like a ninja slicer.

from itertools import islice # This could be any iterable object that doesn't support negative indexing. last_items = list(islice(iterable, None, None, -1))

islice fetches elements in a lazy manner, useful when you're dealing with big data sets or streaming data.

The more_itertools library is another knight in the shining armor. Use it for an enhanced slicing experience:

import more_itertools as mit last_n_items = mit.tail(9, iterable) print(list(last_n_items)) # Retrieves the last 9 items from an iterable

It's like saying, "Hey iterable! Show me your tail."

Best practices

Beware of the Edge (Cases)

Even with Python's forgiving nature, there are edge cases. If the slicing goes overboard, Python won't complain but it may not give you what you expected:

print(items[-10:]) # Returns ['a', 'b', 'c', 'd']

Python being like: "That's all I have, take it."

Keep an eye on performance

Slicing creates a new list. If the original list is Godzilla-sized, you might end up with two monstrous lists in your memory.

# Assume 'huge_list' is a gigantic list with millions of elements last_few = huge_list[-10:] # POOF! Another unnecessary monster arises

In the world of Python, Memory is money!