__getitem__

Dunder MethodPython 2.0+Intermediate

Enables indexing with square brackets (obj[key])

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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.

Try in Playground

Tags

oopmagic-methodprotocolcore