A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/__getitem__-in-python/ below:

__getitem__() in Python - GeeksforGeeks

__getitem__() in Python

Last Updated : 12 Jul, 2025

__getitem__() is a special method (also known as a dunder or magic method) in Python that allows us to access an element from an object using square brackets, similar to how we access items in a list, tuple, or dictionary. It is commonly used to retrieve items from containers or objects that support indexing or key-based access.

Example: Implementing __getitem__ in a Custom Class

Python
class MyList:
    def __init__(self, data):
        self.data = data
    
    def __getitem__(self, index):
        return self.data[index]

# Create an instance of MyList
a = MyList([1, 2, 3, 4, 5])

# Accessing items using square brackets
print(a[2]) 

Explanation:

Syntax

def __getitem__(self, key):

Parameters Return Value

The method must return the value associated with the given key. This value can be any type, depending on the implementation of the __getitem__() method.

Examples of __getitem__() 1. Demonstrating __getitem__() with Various Indexing Types in Python

This code demonstrates the use of the __getitem__() method in Python, which allows an object to define its behavior when accessed using square brackets. The __getitem__() method is invoked whenever an element is accessed with indexing or slicing, enabling custom handling of such operations.

Python
class Test(object): 
	
	def __getitem__(self, items): 
		print (type(items), items) 

# Driver code 
test = Test() 
test[5] 
test[5:65:5] 
test['GeeksforGeeks'] 
test[1, 'x', 10.0] 
test['a':'z':2] 
test[object()] 

Output
<class 'int'> 5
<class 'slice'> slice(5, 65, 5)
<class 'str'> GeeksforGeeks
<class 'tuple'> (1, 'x', 10.0)
<class 'slice'> slice('a', 'z', 2)
<class 'object'> <object object at 0x7fad129141f0>

Explanation:

2. Implementing __getitem__ for Dictionary-Like Access

This code demonstrates how to implement the __getitem__() method in a custom dictionary-like class, allowing access to dictionary values using square brackets while handling missing keys with a KeyError.

Python
class MyDict:
    def __init__(self):
        self.data = {"a": 1, "b": 2, "c": 3}
    
    def __getitem__(self, key):
        if key in self.data:
            return self.data[key]
        else:
            raise KeyError(f"Key '{key}' not found.")

# Create an instance of MyDict
d = MyDict()

# Accessing elements using square brackets
print(d["b"]) 

# print(my_dict["d"])  Raises KeyError: Key 'd' not found.

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4