Meaning
The len() function returns the number of items in a sequence or other sized object. It addresses the need to know a collection's size for iteration, bounds checking, or capacity planning. You reach for len() whenever you must conditionally act on whether a container is empty or when you need to iterate over its indices.
Primary Function
Size retrieval
Communicative Purpose
Ensures you know the exact number of elements before indexing or looping.
Pattern
len(sequence)
Core Structure
len(...)
Função primária
Size retrieval
Propósito comunicativo
Ensures you know the exact number of elements before indexing or looping.
Situações de gatilho
Data processing: checking if a list is empty before processing; File I/O: determining the number of lines read into a buffer; Algorithm design: setting loop bounds for iterating over an array.
Contextos
Ubiquitous in Python codebases, standard library, data science scripts, web backends, and systems programming.
Padrão
len(sequence)
Estrutura central
len(...)
Slots de substituição
sequence: sized object supporting len()
Colocados típicos
- Often used with conditional statements (if len(seq) == 0)
- range-based loops (for i in range(len(seq)))
- and slicing operations (seq[:len(seq)//2]).
Substituições comuns
- Using seq.__len__() (bypasses safety checks
- not idiomatic)
- using pandas .shape[0] for DataFrames (specific to tabular data)
- using length hints via operator.length_hint() (optimization for iterators).
Erros comuns
Calling len() on None – cause: assuming variable is a sequence when it may be None; consequence: TypeError: object of type 'NoneType' has no len(). Using len() on an iterator that has been exhausted – cause: misunderstanding that iterators remain sized; consequence: TypeError or incorrect length (some iterators raise TypeError). Forgetting parentheses and writing len seq – cause: confusion with attribute access syntax; consequence: SyntaxError. Applying len() to a mapping expecting it to return number of keys (actually it does) but confusing with .values() length – cause: misunderstanding of what len counts; consequence: logical error when expecting value count. Using len() on a string to count characters but needing byte length – cause: conflating character count with byte size in Unicode; consequence: off-by errors in encoding-sensitive code.
Similar / contraste
length vs. capacity: capacity reports allocated size, not used size; len() vs. count(): count() counts occurrences of a value; len() vs. __len__(): direct method call bypasses safety checks; len() vs. pandas .shape: shape returns tuple of dimensions.
Interferências
Coming from Java: may use .length property on arrays → In Python use len(obj) for any sized object. Coming from JavaScript: may assume .length works only on arrays → len() works on strings, lists, tuples, dicts, sets, etc.
Família do chunk
- len
- sum
- max
- min
- any
- all
Nuance
Avoid len() on very large lazy iterators where computing length would consume the iterator; it is O(1) for built-in containers but O(n) for some iterators that lack a length hint. Note that len() returns the number of top-level items only, not recursive size of nested structures.
Efeito pragmático
Correct use of len() prevents runtime index errors, enables efficient loop bounds, and makes code intentions clear to readers.
Dica de memória
len() is like asking a librarian how many books are on a shelf — quick, reliable, and tells you whether you need to start reading.
Nota
len() relies on the object's __len__ method; implementing __len__ allows custom objects to work with len() seamlessly.
Log in to save chunks.