Last active
September 6, 2021 07:14
-
-
Save jonbeebe/44a529fcf15d6bda118fe3cfa434edf3 to your computer and use it in GitHub Desktop.
Port of JavaScript Array.prototype.splice() to Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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).