Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
__getitem__ and __setitem__ in Python
In Python, you can customize many operations like accessing or modifying elements of a list or dictionary using special methods. Two important methods that make your objects behave like lists or dictionaries are:
- __getitem__: called when you access an item using obj[key].
- __setitem__: called when you assign a value using obj[key] = value.
These are examples of dunder methods (short for "double underscore"). They are special methods in Python with names that begin and end with double underscores. When you use square bracket syntax on your object:
- obj[key] automatically triggers __getitem__
- obj[key] = value automatically triggers __setitem__
By implementing these methods in your own classes, you can:
- Make your objects act like lists or dictionaries
- Support custom indexing and value assignment
- Access or modify elements using the familiar obj[key] style
Understanding __getitem__
The __getitem__ method is automatically called when you access an element from an object using square brackets. This lets you control how the object returns values for specific keys or indices.
Syntax
def __getitem__(self, key):
# Return the value for the given key
pass
Example: Reading Data with __getitem__
In this example, when we call my_list[1], the __getitem__ method is triggered, and it returns the value at index 1 from the internal list ?
# Define a class that behaves like a list
class MyList:
def __init__(self, data):
self.data = data # Store the data in a list
def __getitem__(self, index):
return self.data[index] # Return the item at the given index
# Create an object with a list of numbers
my_list = MyList([1, 2, 3, 4, 5])
# Access an element using square brackets
print(my_list[1])
print(my_list[0])
print(my_list[4])
The output of the above code is ?
2 1 5
Understanding __setitem__
The __setitem__ method is used when you assign a value to an element using square brackets. This lets you define how new data should be stored or updated inside your object.
Syntax
def __setitem__(self, key, value):
# Set the value for the given key
pass
Example: Updating Data with __setitem__
In this example, my_list[1] = 42 triggers the __setitem__ method, which updates the value at index 1 ?
# Define a class with both getitem and setitem
class MyList:
def __init__(self, data):
self.data = data # Store the data in a list
def __getitem__(self, index):
return self.data[index] # Return the item at the given index
def __setitem__(self, index, value):
self.data[index] = value # Set the item at the given index
# Create an object and access its data
my_list = MyList([1, 2, 3, 4, 5])
print("Before updating:", my_list[1])
# Update the value at index 1
my_list[1] = 42
print("After updating:", my_list[1])
# Update multiple values
my_list[0] = 10
my_list[4] = 50
print("Updated list:", [my_list[i] for i in range(5)])
The output of the above code is ?
Before updating: 2 After updating: 42 Updated list: [10, 42, 3, 4, 50]
Dictionary-like Behavior Example
You can also create classes that behave like dictionaries using string keys ?
class MyDict:
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
# Create a dictionary-like object
my_dict = MyDict()
# Set values using square brackets
my_dict["name"] = "Alice"
my_dict["age"] = 25
# Get values using square brackets
print("Name:", my_dict["name"])
print("Age:", my_dict["age"])
The output of the above code is ?
Name: Alice Age: 25
Key Points
-
__getitem__ enables
obj[key]syntax for retrieving values -
__setitem__ enables
obj[key] = valuesyntax for setting values - These methods work with any type of key (integers, strings, tuples, etc.)
- You can add custom logic like validation or transformation inside these methods
- Objects with these methods can be used in loops and with built-in functions
Conclusion
The __getitem__ and __setitem__ methods allow you to create custom objects that behave like built-in containers. Use __getitem__ to control how values are retrieved and __setitem__ to control how values are stored or updated.
