collections.deque with a maxlen is a list that forgets its oldest items on its own. That makes it a one line tail in Python.
from collections import deque
with open("app.log", encoding="utf-8") as f:
last = deque(f, maxlen=20)
print("".join(last))
The deque reads the whole file line by line, but it never holds more than 20 lines. Once it’s full, every new line pushes the oldest one out the other end. Memory stays flat even on a big log.
I also like it for a rolling window. Keep the last 10 response times in a deque and compare the average with a threshold, and every new measurement automatically replaces the oldest. Same goes for keeping the last few lines of output to show when a long running command fails.
It still reads the file from the start, so on a multi gigabyte log it takes as long as reading the whole thing. The real tail seeks to the end and reads backwards, which is much faster for that case. And indexing into the middle of a deque is slower than with a list. It’s built for adding and removing at the ends, not for d[500].
Further reading: collections.deque