__getitem__ — Easy Examples
Enables indexing with square brackets (obj[key])
Implementing __getitem__
Basic implementation of __getitem__ in a class.
python
class Matrix: def __init__(self, data): self.data = data def __getitem__(self, key): return self.data[key] m = Matrix([[1, 2], [3, 4]]) print(m[0]) print(m[1][0])
__getitem__ enables indexing with square brackets (obj[key]). Implementing it lets you customize how Python interacts with your objects.
__getitem__ in action
Seeing __getitem__ called by Python's built-in operations.
python
# How Python calls __getitem__ automatically class Demo: def __init__(self, value): self.value = value def __getitem__(self, other): print(f"__getitem__ was called!") return self d = Demo(42) # This triggers __getitem__: print(d[0])
Python automatically calls __getitem__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground