Special Method Protocols

__delitem__() — containers protocol

Implement del obj[key]. Select the removed item or slice according to the class contract; invalid keys should raise the appropriate exception.

Formal Syntax & Structure

python syntaxpython
def __delitem__(self, key):

Parameters & Attributes

NameTypeDescription
keyobjectItem or slice to delete.

Return Value

None

No meaningful deletion result.

Working Example

Example Snippetpython
class Bag:    def __init__(self): self.items=[1,2,3]    def __delitem__(self,key): del self.items[key]def demo():    b=Bag(); del b[1]    return b.itemsprint(demo())
Python Reference