How to Truncate a List to Max Length in Python (Keep Head)

This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.

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

Python code

14 lines
Python 3.9+
from typing import List

def truncate_head(lst: List[object], max_length: int) -> List[object]:
    """Return a new list with at most max_length items from the head."""
    if max_length < 0:
        raise ValueError("max_length must be non-negative")
    return lst[:max_length]

if __name__ == "__main__":
    # Example usage
    sample = [1, 2, 3, 4, 5, 6]
    result = truncate_head(sample, 3)
    print(f"Original: {sample}")
    print(f"Truncated: {result}")

Output

stdout
Original: [1, 2, 3, 4, 5, 6]
Truncated: [1, 2, 3]

How it works

Python's slice syntax lst[:max_length] creates a new list containing elements from index 0 up to (but not including) max_length. If max_length is greater than or equal to the list length, the slice returns a copy of the whole list. A negative max_length is invalid because slice semantics would return an empty list silently; raising ValueError makes the function's contract explicit. The function is pure — it doesn't modify the original list, so callers can rely on it without side effects.

Common mistakes

  • Using `lst[:max_length]` with a negative value, which returns an empty list instead of raising an error
  • Forgetting that slicing returns a new list, so modifying the result won't affect the original
  • Assuming the function works for strings or tuples — it works for any sequence, but this code annotates `List`

Variations

  1. Use `lst[:max_length]` directly without a function for simple one-off truncation
  2. Use `itertools.islice` for lazy truncation of very large lists, but it returns an iterator

Real-world use cases

  • Limiting the number of recent log entries displayed in a dashboard to the latest N records.
  • Truncating user activity feeds to show only the most recent items without loading all history.
  • Capping the number of items passed to a batch processing API to avoid oversized payloads.

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.