1

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

2

One way:

deleted = 0
for start, end, replacement in b:
    a[start - deleted:end + 1 - deleted] = replacement
    deleted += (end + 1 - start) - len(replacement)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.