Friday, August 29, 2025
HomeLanguages__getitem__() in Python

__getitem__() in Python

In Python, everything is an object. There are a lot of ‘ordinary’ system call methods on these objects behind the scene which is not visible to the programmer. Here come what are called as magic methods. Magic methods in python are special methods that are invoked when we run any ordinary python code. To differentiate them with normal functions, they have surrounding double underscores.

If we want to add a and b, we write the following syntax:

c = a + b

Internally it is called as:

c = a.__add__(b)

__getitem__() is a magic method in Python, which when used in a class, allows its instances to use the [] (indexer) operators. Say x is an instance of this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i).

The method __getitem__(self, key) defines behavior for when an item is accessed, using the notation self[key]. This is also part of both the mutable and immutable container protocols.

Example:




# Code to demonstrate use
# of __getitem__() in python
  
  
class Test(object):
      
    # This function prints the type
    # of the object passed as well 
    # as the object item
    def __getitem__(self, items):
        print (type(items), items)
  
# Driver code
test = Test()
test[5]
test[5:65:5]
test['Lazyroar']
test[1, 'x', 10.0]
test['a':'z':2]
test[object()]


Output:

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

Unlike some other languages, Python basically lets you pass any object into the indexer. You may be surprised that the test[1, 'x', 10.0] actually parses. To the Python interpreter, that expression is equivalent to this: test.__getitem__((1, 'x', 10.0)). As you can see, the 1, ‘x’, 10.0 part is implicitly parsed as a tuple. The test[5:65:5] expression makes use of Python’s slice syntax. It is equivalent to this expression: test[slice(5, 65, 5)].

The __getitem__ magic method is usually used for list indexing, dictionary lookup, or accessing ranges of values. Considering how versatile it is, it’s probably one of Python’s most underutilized magic methods.

RELATED ARTICLES

Most Popular

Dominic
32248 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11789 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11836 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6686 POSTS0 COMMENTS
Umr Jansen
6699 POSTS0 COMMENTS