You must have used the square bracket notation ([]
) method to access the items from the collection such as list, tuple, or dictionary.
1 2 3 4 |
my_lst = ["Sachin", "Rishu", "Yashwant"] item = my_lst[0] print(item) |
The first element of the list (my_lst
) is accessed using the square bracket notation method (my_list[0]
) and printed in the above code.
But do you know how this happened? When my_lst[0]
is evaluated, Python calls the list’s __getitem__
method.
1 2 3 4 5 |
my_lst = ["Sachin", "Rishu", "Yashwant"] # item = my_lst[0] item = my_lst.__getitem__(0) print(item) |
This is the same as the above code, but Python handles it behind the scenes, and you will get the same result, which is the first element of my_lst
.
You may be wondering what the __getitem__
method is and where it should be used.
The __getitem__ Method
The __getitem__
method is usually implemented within Python classes to make the object of that class work with the square bracket ([]
) notation.
To put it simply, you can use square bracket notation on the class’s objects in the same way that you would with Python’s built-in methods.
1 2 3 4 5 6 7 8 9 10 11 12 |
my_lst = ["Sachin", "Rishu", "Yashwant"] item = my_lst[0] print(item) # Using [] operator on class instance w/o __getitem__ method class Names: def __init__(self): pass friends = Names() result = friends["Sachin", "Rishu", "Yashwant"] |
In the first block of code, the []
operator is used to access a list item.
In the second block of code, a class (Names
) is defined without implementing the __getitem__
method. The []
operator is applied to the class’s object (friends
).
What happens when you run the above code? The first block of code will work because the []
operator is used on the built-in datatype, but the second block of code will fail because the class does not have the __getitem__
method to perform this functionality on the object.
1 2 3 4 5 |
Sachin Traceback (most recent call last): .... result = friends["Sachin", "Rishu", "Yashwant"] TypeError: 'Names' object is not subscriptable |
If you implement the __getitem__
method within the class, the above code will work just fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
... # Using [] operator on class instance with __getitem__ method class Names: def __init__(self): pass # Implemented the __getitem__ method def __getitem__(self, name): print(f'Name: {name[0]}') friends = Names() result = friends["Sachin", "Rishu", "Yashwant"] |
When you run this code, there will be no errors, and the first element will be printed as specified by the __getitem__
method.
1 2 |
Sachin Name: Sachin |
You can see the difference after implementing the __getitem__
method, the object (friends
) is now allowed to access values using the []
operator.
Now how does __getitem__
work? First, let’s understand the syntax of this magic method.
Syntax
__getitem__(self, key)
The __getitem__
method typically accepts a single argument besides self
, which is commonly referred to as key
when dealing with mappings like dictionaries. This argument represents the index or key used to access the value in the object.
Example
Assume you have a large number of entries with employee names and you want to retrieve the first name of each employee from them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class EmployeeFirstName: def __init__(self, file): self.file = file def __getitem__(self, name): with open(self.file, "r") as f: result = f.readlines() first_name = [fname.split()[name] for fname in result] return first_name employee = EmployeeFirstName("employee_data") print("List of Employees First Names:") print(employee[0]) |
The class accepts a file
parameter, and the __getitem__
method opens and reads the file line by line, iterating through each line and splitting it into words with the split()
method before selecting the word at the index name
.
When the class (EmployeeFirstName
) is instantiated, it receives a file (employee_data
), and the square bracket notation ([]
) is used on the instance (employee[0]
) to access the values at the 0th
index from the file.
When you run the code, you will get a list of the employees’ first names from the file.
1 2 |
List of Employees First Names: ['John', 'Cindy', 'Jacob', 'Priya', 'Ivan', 'Ji-min', 'Maria', 'Alexander', 'Li', 'Emily'] |
You were able to access the values because the __getitem__
method was implemented in the class and you can see that the name
argument is used as a key to access values based on the index.
If you change the value of the name to 1
, you will get the employees’ last names.
1 2 3 |
employee = EmployeeFirstName("employee_data") print("List of Employees Last Names:") print(employee[1]) |
Output
1 2 |
List of Employees Last Names: ['Doe', 'Carl', 'Dawson', 'Patel', 'Petrov', 'Kim', 'Garcia', 'Sokolov', 'Wei', 'Johnson'] |
Conclusion
The __getitem__
method is implemented within a Python class, allowing the class object to use square bracket notation ([]
) in the same way that built-in methods do.
You can’t use the []
operator on the instance without implementing the __getitem__
method.
πOther articles you might be interested in if you liked this one
β How to implement getitem, setitem, and delitem in Python classes?
β How to use map() in Python?
β Serialize and deserialize Python objects using the pickle module.
β Why if __name__ == β__main__β is used in Python programs?
β Create a WebSocket server and client in Python.
β Upload and display images on the frontend using Flask.
That’s all for now
Keep Codingββ