__len__ and __getitem__
- Python course
- Intermediate
- Lesson 32/116
- 5 min
Learn sequence behavior with __len__ and __getitem__.
__len__ and __getitem__
__len__(self) gives the result of len(obj). __getitem__(self, index) defines obj[index] access. Together they make a class behave like a sequence.
Example: class Stack:\n def __len__(self):\n return len(self.items)\n def __getitem__(self, index):\n return self.items[index]. len(s) gives the count; s[0] gives the first item. This makes the class behave like built-in sequence types.
Sequence-like usage
Classes with __len__ and __getitem__ can be used like a sequence. len(s), s[0], s[-1] and slicing work. This gives a natural interface for collection classes.
Example: in the Stack class, len(s) gives the item count; s[0] returns the bottom item. A student may think it is a list; but really __getitem__ is called. This way the class follows Python idioms.
Practice Add sequence methods to Stack
Define the Stack class. Add def __init__(self): with self.items = [] in the body. Add def push(self, value): with self.items.append(value). Add def __len__(self): with return len(self.items). Add def __getitem__(self, index): with return self.items[index]. Then call s = Stack(), s.push(1), s.push(2), print(len(s)) and print(s[0]).
Starter code
# Define the Stack classSample solution
# Define the Stack class
class Stack:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[index]
s = Stack()
s.push(1)
s.push(2)
print(len(s))
print(s[0])Expected output
2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the sequence methods
| Term | Meaning |
|---|---|
__len__ |
len() |
__getitem__ |
obj[index] |
len(self.items) |
Inner list size |
2 Which method does len(obj) call?
- __size__
- __length__
- __len__ Correct answer
- __count__
Explanation: The len() function calls the __len__ method.
3 Complete the __getitem__ signature
class Stack:
def __getitem__(self, ____):
return self.items[index]
class Stack:
def __getitem__(self, index):
return self.items[index]
Explanation: __getitem__ takes self and index parameters.