
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 surrounded by double underscores. They are not explicitly called, unlike regular python methods. It is one such magical method __getitem__
method that enables Python objects to behave like a sequence or container, such as lists, dictionaries, and tuples. It takes the index or slice and retrieves its associated value from the collection. It is automatically called when we use indexer [ ]
operator to access the elements of your object.
Think of this method as a magic wand that gives you the power to get the information you need by writing just a few lines of code. Isn’t it interesting? This method is also widely used in data analysis and machine learning. So let’s dive into it __getitem__
method and discover its power and flexibility.
I want you to understand that your responsibility as a Python developer 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 magical method:
- Reduces memory usage by allowing you to extract only key information instead of loading the entire data structure into memory.
- Provides greater flexibility in data processing and manipulation
- Allows you to iterate over a set without rotating the data
- Improves functionality by allowing you to write advanced indexing that is not possible with built-in types
- Simplifies the code because it uses familiar notation
The syntax of __getitem__
the method is as follows.
def __getitem__(self, index):
# Your Implementation
pass
It defines the behavior of the function and takes the index you are trying to access as its parameter. We can use this method as follows:
This translates to a statement my_obj.__getitem__(index)
under the hood. Now you might be wondering how it differs from built-in indexer []
operator? Wherever you use this notation, python automatically calls __getitem__
method for you and is a shorthand for accessing elements. But if you want to change the indexing behavior of custom objects, you must explicitly call __getitem__
method.
Example #01
Let’s start with an easy example first. We’ll create a Student class that will have a list of all the students, and we can access them by index and consider the index to represent their unique student ID.
class Student:
def __init__(self, names):
self.names=names
def __getitem__(self,index):
return self.names[index]
section_A= Student(["David", "Elsa", "Qasim"])
print(section_A[2])
Result:
Now we’ll move to an advanced example where we’ll change the indexing behavior using __getitem__
method. Suppose I have a list of string elements and I want to retrieve the element when I type its index position, and I can also get the index position if I type 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)
else:
raise TypeError("Invalid Argument Type")
my_list = MyList(['red', 'blue', 'green', 'black'])
# Indexing with integer keys
print(my_list[0])
print(my_list[2])
# Indexing with string keys
print(my_list['red'])
print(my_list['green'])
Result:
This method is extremely useful for quickly looking up instance attributes. Given the flexibility and versatility of this method, I’d say it’s one of the most underused magic methods in Python. I hope you enjoyed reading this article and let me know in the comments section if you are interested in learning about other Python magic methods.
Kanwal Mehri is an aspiring software developer with a strong interest in data science and AI applications in medicine. Kanwal has been selected as a Google Generation Scholar 2022 for the APAC region. Kanwal loves sharing technical knowledge by writing articles on cutting-edge topics and is passionate about improving the representation of women in the tech industry.