Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Module

__setitem__

__setitem__ implements assignment through subscription syntax such as obj[key] = value. It is used by mutable mappings and sequences to update, add, or replace stored elements.

How it works

Implement __setitem__ when an object should support assignment through square brackets. The method receives the key and value, then can replace an existing item or add a new one; its validation behavior should align with the corresponding lookup operation.

Syntax

object.__setitem__(self, key, value)

Parameters

NameTypeDescription
selfobjectThe object whose item assignment is being implemented.
keyobjectThe mapping key, sequence index, or slice being assigned.
valueobjectThe replacement or newly assigned value.

Returns

The documentation defines the operation and its arguments but does not specify a return value; implementations conventionally return None.

Key points

  • Python dispatches bracket assignment such as obj[key] = value to obj.__setitem__(key, value).
  • Use it for mutable mappings that can update values or accept new keys.
  • Mutable sequences can implement it to replace elements at valid positions.
  • Keep invalid-key exceptions consistent between assignment and lookup.
  • Slice assignment is part of the same special-method protocol, alongside slice lookup and deletion.

Common mistakes

  • Do not add this method to an immutable mapping; the documentation limits it to objects whose keyed values can change or whose keys can be added.
  • Use the same exception behavior as __getitem__ when a key is invalid.

Example: Custom subscript assignment

class Registry:
    def __init__(self):
        self._items = {}

    def __setitem__(self, key, value):
        if not isinstance(key, str):
            raise TypeError("key must be a string")
        self._items[key] = value

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


registry = Registry()
registry["port"] = 8080
print(registry["port"])

Assignment with square brackets invokes the custom method, which validates the key and stores the value.

When to use it

Mutable mapping

A dictionary-like class validates keys and stores values.

Mutable sequence

A custom list-like class replaces elements by index.

Slice assignment

A container supports assigning a range of elements.

Interview questions

QWhat operation does __setitem__ implement?

__setitem__ is the special method invoked for assignment written as self[key] = value. It receives the key and value and implements the object's storage or validation policy.

Follow-up: How should invalid keys be handled? Raise the same kinds of exceptions that the object's __getitem__ implementation raises for improper keys.

QWhen is implementing __setitem__ appropriate?

A mapping can use it to update an existing value or create a new key. A mutable sequence can use it when an element at a valid position may be replaced.

Follow-up: When should a class omit it? Omit it when keyed values cannot change and new keys cannot be added, or when sequence elements cannot be replaced.

QHow does __setitem__ relate to slicing and other container methods?

Subscription syntax can also use slices, and __setitem__ participates in assigning to those slices. The method must therefore accept and interpret the key or slice according to the container's rules.

Follow-up: Which related methods complete container emulation? __getitem__ handles lookup and __delitem__ handles deletion; collections also provides MutableMapping as an abstract base class.

  • object.__getitem__
  • object.__delitem__
  • collections.MutableMapping

Source: 3. Data model. Checked 2026-10-16.