Skip to content

Instantly share code, notes, and snippets.

@jonbeebe
Last active September 6, 2021 07:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbeebe/44a529fcf15d6bda118fe3cfa434edf3 to your computer and use it in GitHub Desktop.
Save jonbeebe/44a529fcf15d6bda118fe3cfa434edf3 to your computer and use it in GitHub Desktop.
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
@jonbeebe
Copy link
Author

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).

@pchtsp
Copy link

pchtsp commented Sep 6, 2021

Thanks for this function! I advise replacing the delete_count == None for delete_count is None. That's the preferred way python checks for None.

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