len() in Python 2026: Length of Sequences & Modern Patterns & Best Practices
The built-in len() function returns the number of items in a container (list, tuple, string, dict, set, etc.) or the length of user-defined objects that implement __len__(). In 2026 it remains one of the most frequently called built-ins — essential for bounds checking, pagination, data validation, loop control, memory estimation, and ML batch sizing.
With Python 3.12–3.14+ improving container performance, free-threading support for concurrent length queries, and better type hinting for sized objects, len() is faster and safer in modern code. This March 23, 2026 update covers how len() behaves today, real-world patterns, performance notes, and best practices when used with collections, NumPy/JAX arrays, or custom classes in 2026.
TL;DR — Key Takeaways 2026
len(obj)→ returns integer count of items (calls obj.__len__())- Works on: list, tuple, str, dict, set, bytes, array, custom classes with __len__
- 2026 best practice: Prefer len() over manual counting; use with type hints for Sized protocol
- Main use cases: bounds checking, pagination, validation, batch sizing, memory estimation
- Performance: Extremely fast — usually O(1) for built-in types
1. Basic Usage — Length of Common Types
print(len("Hello 2026")) # 10
print(len([1,2,3,4])) # 4
print(len({"a":1, "b":2})) # 2
print(len(set([1,1,2]))) # 2
print(len(range(1000000))) # 1000000 (O(1))
print(len(bytes([0]*100))) # 100
2. Real-World Patterns in 2026
Safe Length Checks & Validation
def process_batch(batch):
if not isinstance(batch, (list, tuple)):
raise TypeError("Batch must be sequence")
n = len(batch)
if n == 0:
return None
if n > 1024:
raise ValueError(f"Batch too large: {n} items")
return sum(batch) / n
Pagination & Slicing Logic
def paginate(items: list, page: int, size: int = 20):
total = len(items)
start = (page - 1) * size
end = min(start + size, total)
return {
"page": page,
"size": size,
"total": total,
"items": items[start:end]
}
ML Batch Length Validation (NumPy/JAX)
import numpy as np
def validate_batch_size(features: np.ndarray, expected: int):
actual = len(features)
if actual != expected:
raise ValueError(f"Batch size mismatch: {actual} vs {expected}")
return True
3. len() vs Alternatives – Comparison 2026
| Approach | O(1)? | Custom types? | Best For |
|---|---|---|---|
| len(obj) | Yes (for most) | Yes (__len__) | Standard length check |
| obj.__len__() | Yes | Yes | Direct call (rare) |
| len(list(obj)) | No | Yes | Avoid — forces materialization |
| obj.size (NumPy/JAX) | Yes | Yes | Array frameworks |
4. Best Practices & Performance in 2026
- Always use len() — never manual counting or len(list(obj))
- Type hints 2026 (Sized protocol):
from typing import Sized def get_length(obj: Sized) -> int: return len(obj) - Performance: len() is O(1) for lists, tuples, dicts, sets, strings — extremely fast
- Free-threading (3.14+): Safe for read-only length queries
- Avoid: len() on generators (forces full consumption)
Conclusion — len() in 2026: Length Check Essential
len() is the idiomatic, efficient way to get the size of containers in Python — used everywhere from validation to pagination to batch processing. In 2026, rely on it with type hints, avoid materializing large iterables, and pair it with modern data tools (NumPy, Polars) for array-level lengths. It’s fast, reliable, and one of Python’s most called built-ins for a reason — simple, consistent, and performant.
Next steps:
- Replace any manual counting with len() in your next loop or validation
- Related articles: Efficient Python Code 2026 • Python Built-ins Overview 2026