Skip to content

Python getitem() method

  • by

The __getitem__() method in Python is a special method that allows objects to support indexing and slicing operations. It is part of the Python Data Model and is used to define custom behavior for accessing items of an object using square bracket notation ([]).

The __getitem__() method syntax in Python is as follows:

def __getitem__(self, key):
    # Custom logic to retrieve the item based on the key
    # Return the retrieved item
  • The method is defined within a class and starts with def.
  • The method name is __getitem__, which is a special method name recognized by Python for indexing and slicing operations.
  • The method takes two parameters: self (a reference to the instance of the class) and key (the index or key used to retrieve the item).
  • Inside the method, you can define your custom logic to retrieve the item based on the provided key.
  • Finally, you return the retrieved item.

Python getitem() method example

Here’s a simple example to demonstrate the __getitem__() method:

class MyList:
    def __init__(self):
        self.items = [1, 2, 3, 4, 5]
    
    def __getitem__(self, index):
        return self.items[index]

my_list = MyList()
print(my_list[2])        
print(my_list[1:4])     

Output:

Python getitem() method

In this example, the MyList class has an internal items list. The __getitem__() method is implemented to retrieve items from this list. When we access elements of my_list using square brackets, the __getitem__() method is automatically called, and the corresponding items or slices are returned.

By defining the __getitem__() method in your custom classes, you can customize the behavior of indexing and slicing to suit your specific needs.

Do comment if you have any doubts or suggestions on this Python method topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading