Lesson 23 of 55
9 mins readPython The splice() Swiss Army Knife
In Plain English
`splice(@array, $offset, $length, @replacements)` is Perl all-in-one array mutation tool, capable of inserting, deleting, or replacing elements at any position.
Deep Dive: How It Works
Syntax: `splice(@arr, $offset, $length, @new_items)`.
Remove Elements: `splice(@arr, 2, 1)` deletes 1 element at index 2.
Insert Without Deletion: `splice(@arr, 1, 0, "inserted")` inserts at index 1.
Return Value: Returns the removed elements as a list.
Core Rules to Remember

Universal Array Editor: Can replicate `pop`, `shift`, `push`, `unshift`, and middle insertions.

In-Place Mutation: Directly modifies the target array.
Live Interactive Example
Hit Run Code to see it liveSplicing Array Elements
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: splice removed 30 and inserted 99, 100 in its place.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Insert Element with splice
Declare `my @items = ("A", "C");`
Use `splice(@items, 1, 0, "B");` to insert "B" at index 1.
Print `"Items: " . join("-", @items) . "\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.