Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Insert and remove elements in a list

Practice inserting an element at a specific position and removing the first occurrence of another element.

Python practice8 minLists & TuplesBeginnerLast updated March 17, 2026

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]

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 1

Input

insert_and_remove([], 0, 'a', 'b')

Output

['a']

Inserting 'a' into an empty list then attempting to remove 'b' (not present) yields ['a'].