Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Make Objects Indexable with __getitem__

Learn to implement __getitem__ so instances behave like sequences with integer indexing, including negative indices.

Python practice15 minMagic Methods & Operator OverloadingIntermediateLast updated April 11, 2026

Problem statement

You will implement a lightweight sequence wrapper class named IndexableList that stores a Python list internally and allows consumers to access elements using square-bracket indexing (obj[index]). Requirements: - Support integer indices (both positive and negative) in __getitem__. - For invalid integer indices (out of range), raise IndexError (same semantics as Python lists). - Type-check the index and raise TypeError for non-integer indices. Do not implement slicing or other behaviors in this exercise — only integer indexing is required.

Task

Implement a class that supports integer indexing (including negative indices) via the __getitem__ magic method.

Examples

Basic indexing

Input

IndexableList([10, 20, 30])[1]

Output

20

Index 1 returns the second element, 20.

Input format

A single expression that evaluates to an element access, e.g. IndexableList([a, b, c])[index].

Output format

The value retrieved by __getitem__; tests compare str(returned_value).

Constraints

- Only integer indices are required (positive and negative). - For non-integer indices, raise TypeError. - For out-of-range indices, raise IndexError.

Samples

Sample 1

Input

IndexableList(['x', 'y', 'z'])[0]

Output

x

Returns the first element 'x'. Strings are compared without quotes in the test harness.