ZetCode

Python __getitem__ Method

Last modified November 17, 2026 Python 3.15

The subscript operator [] calls __getitem__ with the key between the brackets. The key may be an integer, a slice, or any other object the class chooses to accept. This article shows basic indexing, a custom mapping, explicit slice handling, generated values, multi-dimensional keys, and iteration.

Indexing and slicing

obj[key] is evaluated as type(obj).__getitem__(obj, key). Python passes negative indices and slice objects straight through, so delegating to a list gives both behaviours for free.

basic_getitem.py
class Sequence:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        return self.data[index]


s = Sequence([10, 20, 30, 40, 50])
print(s[1])
print(s[-1])
print(s[1:4])
try:
    print(s[10])
except IndexError as e:
    print(type(e).__name__, e)

Index 1 and index -1 return the expected elements, and the slice returns a new list. Reading past the end delegates to the list's own bounds check, which raises IndexError; the example catches it. A robust container should raise IndexError for an out-of-range integer and KeyError for a missing mapping key.

$ python basic_getitem.py
20
50
[20, 30, 40]
IndexError list index out of range

A custom mapping

Mappings use the same hook with non-integer keys. Lowercasing keys on both storage and lookup yields a case-insensitive dictionary; __contains__ makes the in operator work.

custom_dict.py
class CaseInsensitiveDict:
    def __init__(self):
        self._data = {}

    def __getitem__(self, key):
        return self._data[key.lower()]

    def __setitem__(self, key, value):
        self._data[key.lower()] = value

    def __contains__(self, key):
        return key.lower() in self._data


d = CaseInsensitiveDict()
d["Name"] = "John"
print(d["NAME"])
print("name" in d)
try:
    print(d["missing"])
except KeyError as e:
    print(type(e).__name__, e)

A key stored as Name is found as NAME, membership reports True, and a missing key raises KeyError. The hook only needs to perform the lookup; Python uses it for subscript access and __contains__ supplies the in operator.

$ python custom_dict.py
John
True
KeyError 'missing'

Inspecting slice objects

When the key is a slice, its start, stop, and step attributes may be None. Filling in defaults before calling range makes generated sequences behave like normal ones.

slice_handling.py
class Range10:
    def __getitem__(self, key):
        if isinstance(key, slice):
            start = 0 if key.start is None else key.start
            stop = 10 if key.stop is None else key.stop
            step = 1 if key.step is None else key.step
            return list(range(start, stop, step))
        if isinstance(key, int):
            return key * 10
        raise TypeError("key must be int or slice")


r = Range10()
print(r[5])
print(r[1:5])
print(r[1:10:2])

An integer key is multiplied by ten, while slices produce ranges of values. The three slice results show default start, an explicit stop, and a step of two. Checking isinstance(key, slice) is the standard way to separate the two cases.

$ python slice_handling.py
50
[1, 2, 3, 4]
[1, 3, 5, 7, 9]

A virtual sequence

Values do not have to be stored. Here each index is squared on demand, so the sequence has no backing list. Slices still work because the hook builds the requested range.

virtual_sequence.py
class Squares:
    def __getitem__(self, key):
        if isinstance(key, slice):
            start = 0 if key.start is None else key.start
            stop = 10 if key.stop is None else key.stop
            step = 1 if key.step is None else key.step
            return [i ** 2 for i in range(start, stop, step)]
        if isinstance(key, int):
            return key ** 2
        raise TypeError("key must be int or slice")


sq = Squares()
print(sq[5])
print(sq[1:6])
print(sq[1:10:2])

A single index returns its square, and both slices return the corresponding squares. A default stop of 10 keeps the examples bounded; a real infinite sequence would need an explicit end when sliced. This is the same technique used by range-like and generated containers.

$ python virtual_sequence.py
25
[1, 4, 9, 16, 25]
[1, 9, 25, 49, 81]

Multi-dimensional keys

The key can be a tuple, because obj[row, col] passes a two-element tuple to the hook. Unpacking it gives grid-style access while a plain integer can still select a whole row.

matrix.py
class Matrix:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, key):
        if isinstance(key, tuple):
            row, col = key
            return self.data[row][col]
        if isinstance(key, int):
            return self.data[key]
        raise TypeError("key must be int or tuple")


m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(m[1, 2])
print(m[2])

The tuple key returns a single cell and the integer key returns the whole row. The class inspects the key type and raises TypeError for anything else, which keeps mistakes visible.

$ python matrix.py
6
[7, 8, 9]

Iteration through __getitem__

Python can iterate an object without __iter__ by calling __getitem__ with 0, 1, 2, and so on until IndexError is raised. That makes a simple indexable class iterable for free.

iteration.py
class Countdown:
    def __init__(self, start):
        self.start = start

    def __getitem__(self, index):
        if index >= self.start:
            raise IndexError(index)
        return self.start - index


for value in Countdown(4):
    print(value)
print(list(Countdown(3)))

The countdown yields its values in order and list() collects them. Raising IndexError for an index at or past the end is what stops the loop; raising another exception would break iteration.

$ python iteration.py
4
3
2
1
[3, 2, 1]

Best practices

A good subscript hook follows the conventions of built-in containers:

Source

object.__getitem__ - Python documentation

Emulating container types - Python documentation

object.__iter__ - Python documentation

In this article we have implemented the __getitem__ method. We have covered indexing, slicing, mappings, generated sequences, tuple keys, and iteration. For related topics, see Python __setitem__ method, Python __delitem__ method, and Python __len__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.