Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Allow Item Assignment with __setitem__

Implement __setitem__ to support index assignment with auto-expansion behavior.

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

Problem statement

Implement the __setitem__ method for the ExpandableList class so that it behaves like a list for indexing and assignment but with the following extended behavior: - If an assignment uses an index within the current bounds, it replaces the existing element (like a normal list). - If an assignment uses a positive index that is equal to or greater than the current length, the list should be automatically extended with None values to reach that index and then the value should be placed there. Example: assigning to index 3 in a list of length 1 should extend the list to length 4. - Negative indices should behave like Python lists (e.g., -1 refers to the last element). If a negative index is out of range, raise IndexError (the same as a list would). You will complete the TODO in __setitem__. A helper function assign_and_get(initial, index, value) is provided and used in tests.

Task

Write a class that supports indexing and assignment. When assigning past the end, the container should expand filling gaps with None.

Examples

Assign beyond current length

Input

assign_and_get([1, 2], 4, 9)

Output

[1, 2, None, None, 9]

Assigning to index 4 extends the list to length 5, filling gaps with None, then places 9 at index 4.

Input format

A single function call: assign_and_get(initial_list, index, value).

Output format

The function returns the underlying Python list after the assignment.

Constraints

- Do not use built-in list methods that trivially implement the extension behavior for you (you may use append, extend, etc., but the logic must follow the rules). - Maintain the semantics of negative indices as Python lists. - Raise IndexError for out-of-range negative indices as a normal list would.

Samples

Sample 1

Input

assign_and_get(['a','b'], -1, 'z')

Output

['a', 'z']

Negative index -1 replaces the last element.