A have a list of values. I want to remove occurrence of a specific value from the list and insert multiple values where it was previously (the value occurs exactly once). Same thing in code:
values = [1, 2, 3, 4, 5]
index = values.index(3)
values[index:index+1] = ['a', 'b', 'c']
# values == [1, 2, 'a', 'b', 'c', 4, 5]
I don't find it very readable. Is there a built-in method to do this? If not, what would be the best way to turn this into a function?
Here's the best code I came up with:
def splice_by_value(iterable, to_remove, *to_insert):
for item in iterable:
if item == to_remove:
for insert in to_insert:
yield insert
else:
yield item
I'm using Python 3.7.