Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 18

Replace a sublist slice with another list

Medium

20 minute session

Summary

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

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]

Explanation

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 input 0

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

Sample output 0

[9]

Explanation 0

Replacing the whole list with [9].

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:06 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.