len
String & Text Processing

Meaning

Returns the number of items in an object that implements __len__. It provides a quick way to check the size of collections without manual iteration. You reach for it whenever you need to know if a container is empty, bound a loop, or validate input length.

Primary Function

Length measurement

Communicative Purpose

Determines the number of elements in a collection.

Pattern

len(sequence)

Core Structure

len(...)

Função primária

Length measurement

Propósito comunicativo

Determines the number of elements in a collection.

Situações de gatilho

Data processing: checking if a list is empty before iteration; File handling: verifying the number of lines read from a file; String manipulation: validating that a username meets minimum length requirements.

Contextos

Python standard library, data analysis, web development, scripting.

Padrão

len(sequence)

Estrutura central

len(...)

Slots de substituição

sequence: any sized object (list, str, tuple, dict, etc.)

Colocados típicos

  • Used with conditional statements (if len(seq) == 0)
  • loops (for i in range(len(seq)))
  • and slicing (seq[:len(seq)//2]).

Substituições comuns

  • In NumPy
  • prefer .size attribute
  • in JavaScript
  • use .length property
  • manual counting loop as fallback.

Erros comuns

Calling len(None) raises TypeError: object of type 'NoneType' has no len(); Using len on a generator yields TypeError: object of type 'generator' has no len(); Confusing len with capacity (e.g., list capacity vs length).

Similar / contraste

len vs .size in NumPy arrays (.size gives total elements, len gives first dimension); len vs length property in JavaScript strings (both return character count).

Interferências

Coming from JavaScript: may try to access .length directly on Python lists — use len() function instead.

Família do chunk

  • len
  • sum
  • max
  • min
  • any
  • all

Nuance

Do not use on objects without __len__ (e.g., file streams, generators) as it raises TypeError; performance is O(1) for built-in types but may be O(n) for custom objects that compute length; works on any sized object and always returns a non‑negative integer.

Efeito pragmático

Enables constant‑time size checks, preventing off‑by‑one errors and making code clearer than manual counting loops.

Dica de memória

len is like peeking into a bag to see how many items are inside without emptying it.

Frequência: Very highFormulaicidade: FixedTipo de construção: function callPrioridade de aquisição: Automatic productionPrioridade de output: BothTag de espaçamento: Immediate

Log in to save chunks.