Skip to content

Instantly share code, notes, and snippets.

@jonbeebe
Last active September 6, 2021 07:14
Show Gist options
  • 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
@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