Introduction to __getitem__: A Magic Method in Python

Magic methods can make our class design more intuitive by giving us access to Python’s built-in syntax features. In this tutorial, we will study the __getitem__ method for custom indexing.

Introduction to __getitem__: A Magic Method in Python
Image by Author




Python is a magical language with many concepts that even advanced users may not be familiar with. Dunder or Magical methods is one of them. Magic methods are special methods that are surrounded by double underscores. They are not called explicitly unlike the ordinary methods in python. One such magic method is the __getitem__ method, enabling the Python objects to behave like sequences or containers e.g lists, dictionaries, and tuples. It takes the index or slice and retrieves its associated value from the collection. It is invoked automatically whenever we use the indexer [ ] operator to access the elements within your object.

Think of this method as a magic wand that grants you the power to extract the required information just by writing a few lines of code. Interesting right? This method is also used widely in data analysis and machine learning. So, let's dive deeper into the __getitem__ method and discover its power and flexibility.


Benefits of Using __getitem__ Method


I want you to understand that your duty as a Python programmer is more than just writing functional code. Your code should be efficient, readable, and maintainable. Using __getitem__ will help you achieve these goals. Here are some other benefits of using this magic method:

  • Reduces memory usage by allowing you to extract only the essential information instead of loading the complete data structure into the memory
  • Provides greater flexibility in how the data is handled and manipulated
  • Allows you to iterate over the collection without looping over the data
  • Enhances the functionality by allowing you to write advanced indexing that may not be possible with the built-in types
  • Simplifies the code as it uses the familiar notation


Implementing __getitem__ Method


The syntax for the __getitem__ method is as follows:

def __getitem__(self, index):
	# Your Implementation


It defines the behavior of the function and takes the index that you are trying to access in its parameter. We can use this method like this:



This translates to the statement my_obj.__getitem__(index) under the hood. Now you might think that how is it different from the built-in indexer [] operator? Wherever you use this notation, python automatically calls the __getitem__ method for you and is the shorthand for accessing elements. But if you want to change the behavior of indexing for custom objects, you need to explicitly call the __getitem__ method.


Example #01


Let us start with an easy example first. We will create a Student class that will have the list of all the students and we can access them by index and consider that the index represents their unique student ID.

class Student:
    def __init__(self, names):

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

section_A= Student(["David", "Elsa", "Qasim"])





Now we will move over to an advanced example where we will change the indexing behavior using the __getitem__ method. Suppose that I have a list of string elements and I want to retrieve the element whenever I enter its index position and I can also get the index position if I enter the string itself.

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

    def __getitem__(self, index):
        if isinstance(index, int):
            return self.items[index]
        elif isinstance(index, str):
            return self.items.index(index)
            raise TypeError("Invalid Argument Type")

my_list = MyList(['red', 'blue', 'green', 'black'])

# Indexing with integer keys

# Indexing with string keys







This method is extremely useful for the quick lookup of the instance attributes. Considering the flexibility and versatility of this method, I would say this is one of the most underutilized magic methods of Python. I hope you enjoyed reading this article and do let me know in the comment section if you are interested to know about the other magic methods in Python.
Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.