Suppose I have a python list which looks like this:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
And a list of tuples with replacing instructions in the format (starting index, ending index, elements to replace with)
b = [ (2,5,["x","y"]) , (8,8,["z"]) ]
How do I make the substitution without messing with the indices? I've tried but can't get the right approach.
Expected output:
c = [0, 1, "x", "y", 6, 7, "z", 9]
1 Answer 1
One way:
deleted = 0
for start, end, replacement in b:
a[start - deleted:end + 1 - deleted] = replacement
deleted += (end + 1 - start) - len(replacement)
answered Oct 21, 2019 at 15:04
kabanus
26.3k7 gold badges48 silver badges79 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py