Lesson guide
What this Python exercise practices
Insert and remove elements in a list is a beginner practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Practice path
Summary
Practice inserting an element at a specific position and removing the first occurrence of another element.
Problem statement
Write a function insert_and_remove(lst, index, value_to_insert, value_to_remove) that inserts value_to_insert into lst at the given index (like list.insert). After the insertion, remove the first occurrence of value_to_remove from the list if it exists. Return the modified list. Use the same list object (modify in-place) and handle indices that are negative or larger than the list length using Python's list.insert semantics.
Task
Implement a function that inserts a value at a given index and then removes the first occurrence of another specified value, returning the modified list.
Examples
Insert and remove
Input
insert_and_remove([1, 2, 4], 2, 3, 4)
Output
[1, 2, 3]
Explanation
Insert 3 at index 2 -> [1, 2, 3, 4], then remove the first 4 -> [1, 2, 3].
Input format
A function call: insert_and_remove(lst, index, value_to_insert, value_to_remove)
Output format
Return the modified list after insert and remove operations.
Constraints
Perform operations in-place. If value_to_remove is not present, return the list unchanged after insertion.
Samples
Sample input 0
insert_and_remove([], 0, 'a', 'b')
Sample output 0
['a']
Explanation 0
Inserting 'a' into an empty list then attempting to remove 'b' (not present) yields ['a'].
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.