len
Built-in Data Structures

Meaning

Returns the number of keys in a dictionary (or any mapping). Use it when you need to know the size of a dict, e.g., to check if it's empty or to compare sizes.

Primary Function

Size inspection

Communicative Purpose

Report how many items are stored in a mapping

Pattern

len(container)

Core Structure

len(...)

Função primária

Size inspection

Propósito comunicativo

Report how many items are stored in a mapping

Situações de gatilho

Data processing: checking if a dict has entries before processing; Loop control: limiting loops based on dict size; Validation: verifying input dict length before use

Contextos

Python codebases, data processing scripts, API response handling, configuration parsing

Padrão

len(container)

Estrutura central

len(...)

Slots de substituição

container: mapping object (e.g., dict)

Colocados típicos

  • checking if dict is empty with if len(d) > 0
  • iterating over keys with for k in d
  • retrieving values with d.get(k)

Substituições comuns

  • len(my_list)
  • len(my_set)
  • len(my_string)

Erros comuns

Using len on non-iterable objects like integers: cause: passing non-iterable to len; consequence: TypeError. Expecting len to count values instead of keys: cause: misunderstanding len behavior; consequence: incorrect size logic. Calling len on None: cause: passing None; consequence: TypeError.

Similar / contraste

my_dict.__len__() — explicit method call; len(list(my_dict.values())) — counts values (same as keys for dict but differs for other mappings); len(my_dict.keys()) — redundant call.

Interferências

Coming from JavaScript: you might think to use Object.keys(my_dict).length → use len(my_dict); Coming from Java: you might think to use my_dict.size() → use len(my_dict).

Família do chunk

  • len
  • sum
  • any
  • all

Nuance

When NOT to use: when you need to count values or nested items, or when __len__ may be expensive; Performance: O(1) for built-in mapping types, depends on __len__ implementation for user-defined types; Boundary conditions: raises TypeError for non-sized objects, returns 0 for empty containers, does not count nested elements.

Efeito pragmático

Provides instant, readable size check; avoids manual iteration and potential off-by-one errors.

Dica de memória

Think 'length' → len(container).

Nota

len operates in O(1) time for built-in mapping types; for user-defined types performance depends on their __len__ implementation.

Upgrade path

Using collections.Counter for frequency counts

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

Log in to save chunks.