Truncate List Keeping Last N Elements in Python

Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 12 views 0 copies

Python code

12 lines
Python 3.9+
def truncate(seq, keep_last_n):
    """Return a new list keeping only the last n elements."""
    if keep_last_n <= 0:
        return []
    return list(seq)[-keep_last_n:]


if __name__ == "__main__":
    data = [10, 20, 30, 40, 50, 60]
    print(truncate(data, 3))
    print(truncate(data, 0))
    print(truncate(data, 10))

Output

stdout
[40, 50, 60]
[]
[10, 20, 30, 40, 50, 60]

How it works

The function accepts any sequence and converts it to a list using list(seq). Slicing with a negative index like [-keep_last_n:] captures the last n items. A guard for keep_last_n <= 0 ensures we return an empty list rather than an unexpected slice. When keep_last_n exceeds the sequence length, Python silently returns the whole list, which is usually the desired behavior.

Common mistakes

  • Using `keep_last_n > len(seq)` without handling it — Python returns the full list, which may or may not be intended.
  • Forgetting the `keep_last_n <= 0` guard and using a negative index that behaves incorrectly.
  • Assuming the function mutates the original list instead of returning a new one.

Variations

  1. Use `seq[-keep_last_n:]` directly on a list if you know it's already a list and don't need the guard.
  2. Create a generator-based version using `collections.deque(seq, maxlen=n)` for memory efficiency on large iterables.

Real-world use cases

  • Keeping only the most recent 10 sensor readings from a live data stream before plotting.
  • Limiting the last 100 log lines from a file to display in a monitoring dashboard.
  • Retaining the final 5 items from a paginated API response for a 'recent items' preview.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.