Meaning
len() returns the number of items stored in a container that implements the Sized protocol. It lets developers quickly determine collection size without manual iteration, avoiding O(N) counting loops. Use it whenever you need the length of a list, tuple, string, dict, set, or any custom object that defines __len__.
Primary Function
Querying container size
Communicative Purpose
Obtain the length of a list, tuple, string, dict, set, or any object implementing the Sized protocol.
Pattern
len(iterable)
Core Structure
len(...)
Função primária
Querying container size
Propósito comunicativo
Obtain the length of a list, tuple, string, dict, set, or any object implementing the Sized protocol.
Situações de gatilho
Data analysis: determining the number of rows in a list before processing; Web development: validating that a request payload does not exceed a maximum length
Contextos
General Python scripts, data‑processing pipelines, algorithm implementations, web back‑ends.
Padrão
len(iterable)
Estrutura central
len(...)
Slots de substituição
iterable: any object that implements the Sized protocol (e.g., list, tuple, dict, string, set, custom class)
Colocados típicos
- list
- tuple
- dict
- string
- set
- range
- custom collection classes
Substituições comuns
- obj.__len__()
- sum(1 for _ in obj) for iterables without __len__
- len(list(obj)) after materialising an iterator
Erros comuns
Calling len on a generator or iterator (TypeError), forgetting the parentheses (len vs len), using len on an integer, assuming O(N) cost for custom lenlenlen implementations.
Similar / contraste
Using obj.__len__() directly bypasses the built‑in, while size() is common in C++ STL containers; len() is Python‑specific.
Interferências
Coming from C/C++: confusing len() with sizeof, which yields byte size at compile time.
Família do chunk
- built‑in functions
- collection utilities
- sequence protocols
Nuance
len() runs in O(1) for built‑in containers but may be O(N) for user‑defined __len__ methods; avoid calling len on large lazy iterables without materialising them.
Efeito pragmático
Enables constant‑time size checks, simplifies loops and bounds validation, and makes code intent explicit.
Dica de memória
Think of "len" as the shortcut for "length" of a collection.
Nota
len() is a built‑in function that invokes the object's __len__ method; it cannot be used directly on generators or iterators lacking __len__ (use sum(1 for _ in gen) instead).
Upgrade path
Use collections.abc.Sized to type‑check objects or operator.length_hint for iterables lacking __len__.
Log in to save chunks.