Meaning
Returns the number of items in a container such as a string, list, tuple, dict, or set, or any object that defines __len__. It is used to check size before iterating, indexing, or allocating space. You reach for len when you need to know how many elements are present to avoid index errors or to validate input.
Primary Function
Compute the length/size of an object.
Communicative Purpose
Query the size of a container to inform loops, indexing, or conditionals.
Pattern
len(container)
Core Structure
len(...)
Função primária
Compute the length/size of an object.
Propósito comunicativo
Query the size of a container to inform loops, indexing, or conditionals.
Situações de gatilho
Python: checking the length of a list before looping to avoid index errors; Python: validating that input data meets a minimum size requirement in a function; Python: determining the number of characters in a string for slicing operations
Contextos
Loop bounds, slicing, precondition checks, allocating buffers, validating input size.
Padrão
len(container)
Estrutura central
len(...)
Slots de substituição
container: any object defining __len__ (e.g., list, str, tuple, dict, set)
Colocados típicos
- list
- string
- tuple
- dict
- set
- range
- bytes
- bytearray
- memoryview.
Substituições comuns
- length
- size
- count (in other languages).
Erros comuns
Applying len to non‑sized objects (int, None, float) → TypeError; confusing with .length property from other languages.
Similar / contraste
len vs. size (other languages); len vs. __len__ (customizing length)
Interferências
Coming from Java: may mistakenly use .length on strings/arrays; in Python use len(). Coming from C: may confuse sizeof with len; sizeof gives bytes, len gives element count.
Família do chunk
- len
- sum
- min
- max
- any
- all
Nuance
(1) Do not use len on non‑sized objects like integers or None; (2) For built‑in types len is O(1), but for user‑defined __len__ it may be O(n); (3) Returns 0 for empty containers and raises TypeError for unsupported types.
Efeito pragmático
enables correct indexing and prevents IndexError
Dica de memória
len is like asking a container how many items it holds, like asking a bag how many marbles inside.
Nota
len returns an int ≥ 0 and works with any object that defines __len__.
Upgrade path
Using enumerate to get both index and value while iterating.
Log in to save chunks.