Array.prototype.splice() in Python

I’ve been digging into Python 3 lately, and so far I’m really liking it. One of the things I miss coming from JavaScript, however, is Array.prototype.splice(). Although Python’s list (and string) slicing syntax is really convenient, things seemed to get unnecessarily complicated when I wanted to insert and remove items at an arbitrary position within a list. The simple one-liner I was used to in JavaScript became a multi-line affair in Python.

Given the breadth of Python’s standard library, I was surprised I couldn’t find the same functionality buried somewhere. And while it’s possible it’s there and I just haven’t looked hard enough, I thought it might be fun to port over JavaScript’s implementation anyway.

Here it is (also available as a Gist):

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

I tried to be as close to the JavaScript implementation’s behavior as possible (and as in JavaScript, the target list is mutated). Here’s an example:

arr = ['a', 'b', 'c', 'd', 'e', 'f']
removed = list_splice(arr, 2, 3, 'x', 'y', 'z')
print("modified:", arr)
print("removed:", removed)


modified: ['a', 'b', 'x', 'y', 'z', 'f']
removed: ['c', 'd', 'e']
HostGator $3.96

$3.96 for web hosting – used by Get started today.