Problem No 18
Replace a sublist slice with another list
Medium≈ 20 minute session
Lesson guide
What this Python exercise practices
Replace a sublist slice with another list is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 20 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 20 minutes
Practice path
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].
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.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.