Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Replace a sublist slice with another list

Replace a slice of a list with the contents of another list, following Python slice semantics.

Python practice20 minLists & TuplesIntermediateLast updated March 17, 2026

Problem statement

Create replace_slice(lst, start, end, replacement) that returns a new list where the slice lst[start:end] (using Python's slicing rules: start inclusive, end exclusive; start or end may be None or negative) is replaced by the elements from replacement (a list). Do not modify the original list. The function should follow Python's semantics for slices, including inserting when the slice is empty.

Task

Understand Python slice semantics and learn how to replace parts of a list safely, returning a new list.

Examples

Replace a middle slice

Input

replace_slice([1,2,3,4,5], 1, 3, [9,9])

Output

[1, 9, 9, 4, 5]

Elements at indices 1 and 2 are replaced by [9,9].

Input format

Four arguments: a list, start index (or None), end index (or None), and a replacement list.

Output format

A new list with the specified slice replaced by the replacement contents.

Constraints

Follow Python's list slicing semantics exactly. Do not modify the input list.

Samples

Sample 1

Input

replace_slice([1,2,3], None, None, [9])

Output

[9]

Replacing the whole list with [9].