0
0
PythonHow-ToBeginner · 3 min read

How to Implement __getitem__ in Python: Simple Guide

To implement __getitem__ in Python, define this method inside your class to accept an index or key and return the corresponding value. This allows your objects to use square bracket notation like lists or dictionaries.
📐

Syntax

The __getitem__ method takes one parameter, usually called key or index, which represents the item requested inside square brackets. It should return the value for that key or index.

Example parts:

  • def __getitem__(self, key): — method header
  • key — the index or key used in square brackets
  • return — the value to give back for that key
python
class MyClass:
    def __getitem__(self, key):
        # return value for key
        pass
💻

Example

This example shows a class that stores a list and lets you get items using square brackets like a list.

python
class MyList:
    def __init__(self, items):
        self.items = items

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

my_list = MyList([10, 20, 30])
print(my_list[0])  # prints 10
print(my_list[2])  # prints 30
Output
10 30
⚠️

Common Pitfalls

Common mistakes when implementing __getitem__ include:

  • Not handling invalid keys or indexes, which causes errors.
  • Forgetting to support slicing if needed (slices are passed as slice objects).
  • Returning wrong types or not raising IndexError or KeyError when appropriate.

Example of handling slices:

python
class MyList:
    def __init__(self, items):
        self.items = items

    def __getitem__(self, index):
        if isinstance(index, slice):
            return self.items[index]
        elif isinstance(index, int):
            if index < 0 or index >= len(self.items):
                raise IndexError('Index out of range')
            return self.items[index]
        else:
            raise TypeError('Invalid argument type')
📊

Quick Reference

Tips for implementing __getitem__:

  • Always accept one parameter besides self, which is the key or index.
  • Support int for single items and slice for slices if your object is sequence-like.
  • Raise IndexError or KeyError for invalid keys.
  • Return the correct value for the given key.

Key Takeaways

Implement __getitem__(self, key) to enable square bracket access on your objects.
Handle both integer indexes and slice objects for flexible access.
Raise appropriate errors like IndexError or KeyError for invalid keys.
Return the correct value corresponding to the given key or index.
Supporting __getitem__ makes your class behave like built-in containers.