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.
Python code
14 linesfrom 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
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
- Use `lst[:max_length]` directly without a function for simple one-off truncation
- 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
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.