easy +5 pts

Insert New Row

Take a 2D list and insert a new row at a given position.

Write a function `insert_row(matrix, row, index)` in Python that takes a list of lists (representing a matrix), a new row (a list), and an integer index, and returns a new matrix with the new row inserted at the given index. The insertion follows the same rules as `list.insert`: - If `index` is non-negative, the row is inserted so that it appears before the row currently at that index (indexing from 0). - If `index` is negative, it counts from the end (e.g., -1 inserts before the last row). - Any index beyond the bounds will insert at the beginning or end respectively, consistent with Python's `list.insert` behavior. The original matrix and row should remain unchanged; the function must return a new matrix (shallow copy of rows is acceptable).

Constraints

`matrix` is a list of lists, possibly empty. The row is a list (may be empty). The index is an integer. Time complexity: O(n) as list insertion, space O(1) for references (not counting output).

Example

```python
>>> insert_row([[1,2],[3,4]], [9,9], 1)
[[1,2],[9,9],[3,4]]
>>> insert_row([], [5,6], 0)
[[5,6]]
>>> insert_row([[1,2],[3,4]], [7,8], -1)
[[1,2],[7,8],[3,4]]
>>> insert_row([[1,2],[3,4]], [0], 10)
[[1,2],[3,4],[0]]
```
5 points ~5 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Make a copy of the matrix using `matrix.copy()` or `list(matrix)` to avoid modifying the original.
Use the list `.insert(index, row)` method on the copied list.
Remember that this should work for empty matrices and out-of-range indices.
Think about how Python's list.insert handles negative indices—you don't need to do anything special.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.