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.
Python code
12 linesdef 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
[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
- Use `seq[-keep_last_n:]` directly on a list if you know it's already a list and don't need the guard.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.