5 Best Ways to Get Last N Elements from a Given List in Python

πŸ’‘ Problem Formulation: You have a list in Python and you need to retrieve the last ‘n’ elements where ‘n’ is a dynamic value specified at runtime. For instance, if you have a list [2, 4, 6, 8, 10, 12] and you want to get the last 3 elements, the desired output should be [8, 10, 12].

Method 1: Using Negative Slicing

Python’s list slicing feature allows you to obtain a sub-list from the main list using indices. Negative slicing, where you specify a negative start index, is particularly useful for getting the last ‘n’ elements. This method is intuitive and works directly with the list’s structure.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

my_list = [1, 2, 3, 4, 5, 6]
last_three = my_list[-3:]
print(last_three)

Output: [4, 5, 6]

This code snippet uses the slicing syntax my_list[-3:] to create a new sub-list starting from the third last element to the end of the list, effectively fetching the last three elements.

Method 2: Using list[-n:] with len()

If you have the number of elements ‘n’ to be fetched at runtime and want to make it very explicit, you can use len(list) minus ‘n’ to indicate the starting index. It is a slightly longer form but clearer to those new to Python.

Here’s an example:

my_list = ['a', 'b', 'c', 'd', 'e']
n = 2
last_n_elements = my_list[-n:] if n <= len(my_list) else my_list
print(last_n_elements)

Output: ['d', 'e']

The code determines the slicing start index by subtracting ‘n’ from the length of the list. A condition is also included to return the entire list if ‘n’ is larger than the list’s length, which prevents errors.

Method 3: Using itertools.islice()

The itertools.islice() function allows for efficient slicing of any iterable. When you need to handle large lists or generators and want to avoid copying elements (as slicing does), this can be a memory-efficient alternative.

Here’s an example:

from itertools import islice

my_list = range(1, 11)  # A range representing a list of numbers from 1 to 10
n = 4
last_n_elements = list(islice(my_list, len(my_list) - n, None))

print(last_n_elements)

Output: [7, 8, 9, 10]

This snippet uses islice() to obtain an iterator from the specified range within the list without actually creating a sub-list, making it a memory-efficient option for large lists.

Method 4: Using deque from collections with maxlen

The collections.deque with a specified maxlen creates a double-ended queue where you can preserve only a limited number of elements. This method is useful when you want to keep adding elements to a list but only care about the last ‘n’ elements.

Here’s an example:

from collections import deque

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3
d = deque(my_list, maxlen=n)

print(list(d))

Output: [8, 9, 10]

Creating a deque with a maxlen automatically ensures it only holds the last ‘n’ elements of the given list. This can be especially powerful in streaming data scenarios.

Bonus One-Liner Method 5: Using lambda function

A one-liner using a lambda function allows for a quick and concise way of getting the last ‘n’ elements. This method leverages the power of Python’s functional programming features for a compact solution.

Here’s an example:

my_list = [10, 20, 30, 40, 50, 60]
n = 3
last_n = lambda lst, n: lst[-n:]

print(last_n(my_list, n))

Output: [40, 50, 60]

The lambda function defined here takes two parameters: the list and the number of elements to return. It then uses list slicing within the function body to achieve the result.

Summary/Discussion

  • Method 1: Negative Slicing. Simple and intuitive. Might not be clear to beginners how negative indices work.
  • Method 2: Using len(). More explicit, good for clarity. Slightly more verbose and includes a conditional check.
  • Method 3: itertools.islice(). Memory-efficient, excellent for large lists and when dealing with iterators. Not as straightforward and requires importing itertools.
  • Method 4: collections.deque. Great for fixed-size queues and data stream scenarios. Not suitable for all cases as it modifies the original list structure.
  • Method 5: Lambda function. Compact and Pythonic for quick one-off tasks. Might be less readable for those not familiar with lambda functions and can be an overkill for simple actions.