Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Port of JavaScript Array.prototype.splice() to Python 3
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
Owner

jonbeebe commented Mar 29, 2017

Updated the gist to remove the loop at the end (which called insert() for each of the *items). I just learned that slices can be assigned to which is a much better way to accomplish that same thing (line 17).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment