How to Keep a History of the Last n Items in Python

If I would like to keep a history of the last n number of items that have been seen during iteration or some other kind of processing.

A limited history can be maintained using the deque data structure within the collections module. The code below performs a word match from within the words.txt file used within this site's Countdown: Letters Game application.

It yields the matching line from the file and the previous 10 lines. The default number of historic lines to use in cases where the third parameter is not submitted to the 'search' function is 5.

from collections import deque

def search(lines, word, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if word in line:
            yield line, previous_lines
        previous_lines.append(line)


if __name__ == "__main__":
    with open('countdown_letters/words.txt') as f:
        for line, prevlines in search(f, 'python', 10):
            for pline in prevlines:
                print(pline, end='')
            print(line, end='')
            print('-' * 20)

The final print functions just return some formatting for the outputted text to the terminal.