__setitem__Easy Examples

Enables item assignment with square brackets (obj[key] = value)

Implementing __setitem__

Basic implementation of __setitem__ in a class.

python
class SafeList:
    def __init__(self):
        self._data = {}

    def __setitem__(self, key, value):
        self._data[key] = value
        print(f"Set [{key}] = {value}")

    def __getitem__(self, key):
        return self._data[key]

sl = SafeList()
sl["name"] = "Python"
print(sl["name"])

__setitem__ enables item assignment with square brackets (obj[key] = value). Implementing it lets you customize how Python interacts with your objects.

__setitem__ in action

Seeing __setitem__ called by Python's built-in operations.

python
# How Python calls __setitem__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __setitem__(self, other):
        print(f"__setitem__ was called!")
        return self

d = Demo(42)
# This triggers __setitem__:
print(d)

Python automatically calls __setitem__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground