__getitem__
__getitem__ is a Python special method that defines subscription access to an object's elements using square-bracket notation.
The Quick Python Book, Fourth Edition
__getitem__ is a Python special method that defines how an object responds when an item or slice is accessed with subscription syntax.
- How it is used
- Enables user-defined objects to support indexed access and, in the sequential example, iteration.
- How deep it goes
- Explains subscription dispatch, sequential iteration, and `IndexError` termination, then contrasts narrow iteration with index-aware list behavior.
- Examples
- Uses a line-by-line file reader and a type-checked list backed by a regular list.
- What you can do after
- Build it from scratch: define indexed access for a class and use `IndexError` to end sequential iteration.
Read how The Quick Python Book, Fourth Edition explains __getitem__ →
Deep Learning with PyTorch, Second Edition
A Python special method that retrieves an item by index or key, used here by Dataset to return a sample and label.
- How it is used
- Provides indexed access to individual samples for PyTorch Dataset objects used in image classification and custom training or validation datasets.
- How deep it goes
- Defines the index contract and demonstrates sample construction, tensor conversion, dimensions, and multi-value returns without descending into method internals.
- Examples
- Uses CIFAR-10 image access and a LunaDataset tuple containing tensors, a series identifier, and coordinates.
- What you can do after
- Apply it via PyTorch Dataset subclassing to retrieve and format indexed samples for training or validation.
Read how Deep Learning with PyTorch, Second Edition explains __getitem__ →
Related concepts
- datasetimplemented by · A dataset is an organized collection of related data items, records, or observations treated as a unit for storage, processing, analysis, or computation.
- loopused by · A loop is a programming control-flow construct that repeatedly executes a block of instructions according to an iteration rule or continuation condition.
- square bracketsequivalent to · Square brackets are paired punctuation marks used in programming-language syntax to delimit expressions or constructs, including indexing and collection literals.
- iterableimplements · An iterable is an object or value that provides or supports a protocol for producing its elements sequentially.
- special methodkind of · A special method is a Python method with a conventionally reserved name that defines an object's behavior for language operations or built-in functions.
- functionkind of · A function is a callable program unit that performs an operation, may accept inputs, and can produce a result or side effect.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

