Python: Keep Last N Items of a List, Array or String

When processing data in Python, we often want to maintain a subset of the most recent elements from a collection. Whether it’s a list, NumPy array, or a string, there are various ways to achieve this efficiently.

This tutorial will explore different methods to keep the last N items using the deque from the collections module, standard Python lists, NumPy arrays, and strings.

Approach/DataTypeWhen to Use?Example
dequeElements are added one added time (in loop)q = deque(maxlen=3)
q.append(item)
listWhen the number of items to retain is relatively smalllast_n_items_list = my_list[-3:]
Numpy ArrayFor mathematical operations and large datasetslast_n_items_array = my_array[-3:]
stringWhen working with textual data or log fileslast_n_chars = my_string[-3:]

1. Keeping Last N Items using deque

The deque (double-ended queue) is a versatile data structure that allows efficient appending and popping from both ends. This can be used for keeping track of the last N items added to it.

In this example, we create a deque q with a maximum length of 3. As elements are appended, the deque automatically removes the oldest elements when the maximum length is reached.

from collections import deque

q = deque(maxlen=3)

q.append(1)
q.append(2)
q.append(3)
print(q)	# deque([1, 2, 3], maxlen=3)

q.append(4)
print(q)	# deque([2, 3, 4], maxlen=3)

q.append(5)
print(q)	# deque([3, 4, 5], maxlen=3)

2. Finding Last N Items from a List

While Python lists don’t have a built-in mechanism for maintaining a maximum length, we can achieve the same result using list slicing. Use this approach when the number of items to retain is relatively small.

In this example, we use list slicing to obtain the last three items from the list.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
last_n_items_list = my_list[-3:]

print(last_n_items_list)	# [7, 8, 9]

3. Finding Last N Items from NumPy Arrays

For numerical data and more advanced operations, NumPy arrays provide an efficient solution. We can use array slicing to obtain the last N elements.

Use this approach for mathematical operations and large datasets.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
last_n_items_array = my_array[-3:]

print(last_n_items_array)	# [7, 8, 9]

4. Keeping the Last N Characters of a String

When we need to retain the last N characters from a string, the string slicing is handy for this task. We can use this approach when working with textual data or log files, where the recent information is crucial.

In this example, we use string slicing to keep the last six characters of the string my_string.

my_string = "Hello, World!"
last_n_chars = my_string[-6:]

print(last_n_chars)	# World!

5. Conclusion

This tutorial discussed different approaches to keep track of the last N items. Depending on the specific requirements and the type of data you’re working with, you can choose the most suitable approach.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode