Python __setitem__ Method
Last modified November 18, 2026 Python 3.15
The expression obj[key] = value calls
obj.__setitem__(key, value). Implementing it turns a class into a
mutable container. The hook receives a single key, which may be an integer, a
slice, a tuple or any other object. This article covers a basic mapping, slice
assignment, validation, two-dimensional indexing, a logging proxy, an
append-only container and normalized keys.
A basic mapping
A dictionary-like class stores values in an internal dict. The hook
prints the assignment, then performs it; __getitem__ completes
the minimal container protocol.
class SimpleDict:
def __init__(self):
self._data = {}
def __setitem__(self, key, value):
print("setting", key, "to", value)
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
d = SimpleDict()
d["name"] = "Alice"
d["age"] = 30
print(d["name"], d["age"])
Both assignments passed through __setitem__ and the values were
retrieved with __getitem__. This is the smallest useful mutable
mapping.
$ python basic.py setting name to Alice setting age to 30 Alice 30
Sequence assignment and slices
For a sequence, the key can be an integer index or a slice.
Delegating to the underlying list handles both cases, including replacing a
range with a different number of values.
class MyList:
def __init__(self, items=None):
self._items = list(items) if items is not None else []
def __setitem__(self, index, value):
self._items[index] = value
def __getitem__(self, index):
return self._items[index]
def __repr__(self):
return repr(self._items)
items = MyList([1, 2, 3])
items[1] = 99
items[0:2] = [7, 8, 9]
print(items)
print(items[0], items[-1])
A single index replaced one value, while the slice replaced two values with three and shifted the rest. The slice object reached the hook unchanged; the list did the actual work.
$ python sequence.py [7, 8, 9, 3] 7 3
Validating values
A container can reject values that do not meet its rules. The check happens before the value is stored, so a failed assignment leaves the container untouched.
class NumericDict:
def __init__(self):
self._data = {}
def __setitem__(self, key, value):
if not isinstance(value, (int, float)) or isinstance(value, bool):
raise ValueError("only numeric values allowed")
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
nd = NumericDict()
nd["age"] = 25
print(nd["age"])
for bad in ("Bob", True):
try:
nd["x"] = bad
except ValueError as e:
print(type(e).__name__, e)
Booleans were rejected explicitly even though they are integers in Python. Such constraints are straightforward to enforce at the assignment boundary.
$ python validation.py 25 ValueError only numeric values allowed ValueError only numeric values allowed
Two-dimensional indexing
A tuple key can represent multiple indices. The hook unpacks it and checks each component before writing to the backing grid.
class Matrix:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self._data = [[0] * cols for _ in range(rows)]
def __setitem__(self, key, value):
row, col = key
if not (0 <= row < self.rows and 0 <= col < self.cols):
raise IndexError("matrix indices out of range")
self._data[row][col] = value
def __getitem__(self, key):
row, col = key
return self._data[row][col]
m = Matrix(2, 2)
m[1, 1] = 5
print(m[1, 1])
try:
m[0, 2] = 3
except IndexError as e:
print(type(e).__name__, e)
The valid assignment succeeded; the second one raised
IndexError because column 2 is outside a two-column matrix. The
tuple in m[1, 1] arrived as a single key argument.
$ python matrix.py 5 IndexError matrix indices out of range
A logging proxy
A proxy can add behaviour to an existing container without changing its class. Here assignments are logged and then forwarded to the wrapped list.
class LoggingListProxy:
def __init__(self, original):
self._original = original
def __setitem__(self, index, value):
print("setting index", index, "to", value)
self._original[index] = value
def __getitem__(self, index):
return self._original[index]
def __repr__(self):
return repr(self._original)
original = [1, 2, 3]
proxy = LoggingListProxy(original)
proxy[1] = 99
print(original)
The original list changed even though the assignment went through the proxy. This is useful for adding logging, validation or access control to a third-party container.
$ python proxy.py setting index 1 to 99 [1, 99, 3]
An append-only container
The hook can enforce a policy over time. After the container is sealed, existing indices may be updated but new positions are refused.
class FixedSize:
def __init__(self, *values):
self._items = list(values)
self._sealed = False
def seal(self):
self._sealed = True
def __setitem__(self, index, value):
if index < 0:
index += len(self._items)
if self._sealed and not 0 <= index < len(self._items):
raise IndexError("cannot extend a sealed container")
self._items[index] = value
def __repr__(self):
return repr(self._items)
box = FixedSize(1, 2, 3)
box[0] = 9
box.seal()
box[-1] = 8
try:
box[5] = 0
except IndexError as e:
print(type(e).__name__, e)
print(box)
Updating existing positions — including a negative index — still worked
after sealing, while an out-of-range write was refused. The rule is enforced
entirely in __setitem__.
$ python append_only.py IndexError cannot extend a sealed container [9, 2, 8]
Normalized mapping keys
A mapping can normalize keys on the way in and the way out. Lower-casing keys makes lookups case-insensitive while storing one canonical entry.
class CaseInsensitiveDict:
def __init__(self):
self._data = {}
def __setitem__(self, key, value):
self._data[key.lower()] = value
def __getitem__(self, key):
return self._data[key.lower()]
def __repr__(self):
return repr(self._data)
d = CaseInsensitiveDict()
d["Name"] = "Alice"
d["NAME"] = "Bob"
print(d)
print(d["name"])
Both assignments targeted the same canonical key, so the second overwrote the first. Reading with any capitalization found the stored value.
$ python normalized_keys.py
{'name': 'Bob'}
Bob
Best practices
A few rules keep __setitem__ predictable:
- Accept any key type the container claims to support, including slices and tuples.
- Validate before writing so rejected assignments leave the container unchanged.
- Keep
__setitem__consistent with__getitem__and__delitem__. - Delegate complex slice logic to the underlying list when possible.
- Decide explicitly whether negative indices and out-of-range keys are allowed.
Source
object.__setitem__ - Python documentation
Mapping types - Python documentation
Subscriptions - Python documentation
In this article we have implemented the __setitem__ method. We
have covered basic mappings, slices, validation, two-dimensional keys,
proxies, append-only containers and normalized keys. For related topics, see
Python __getitem__ method,
Python __delitem__ method, and
Python operators.
Author
List all Python tutorials.