Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Support Slicing in __getitem__ for a Sequence

Extend indexing to accept slice objects so your sequence supports ranges, steps, and omitted bounds.

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

Problem statement

Enhance a sequence wrapper, SliceableList, so that accessing it with a slice (e.g., obj[1:4], obj[:], obj[::2]) returns a new list containing the selected elements. The class should also continue to support integer indexing. Requirements: - If key is an int, return the corresponding element (support negative indices as Python lists do). - If key is a slice, return a new list corresponding to self._items[key] (preserve Python slicing semantics for start, stop, step, negative steps, and out-of-range bounds). - For other key types, raise TypeError. Returning a list for slices keeps behavior simple and predictable for callers and tests.

Task

Implement __getitem__ that accepts both integer indices and slice objects; slice results should return a standard Python list.

Examples

Slice with step

Input

SliceableList([0, 1, 2, 3, 4, 5])[::2]

Output

[0, 2, 4]

A step of 2 selects every second item starting at index 0.

Input format

Expressions like SliceableList([...])[start:stop:step] or SliceableList([...])[index].

Output format

The returned element (for integer index) or a list (for slice). Tests compare str(returned_value).

Constraints

- Must support both int and slice keys in __getitem__. - For slices, return a Python list containing the selected items. - For unsupported key types, raise TypeError.

Samples

Sample 1

Input

SliceableList(["a", "b", "c", "d"])[1:3]

Output

['b', 'c']

Slicing from 1 (inclusive) to 3 (exclusive) returns ['b', 'c'].