0

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.

gronostaj
  • 2,231
  • 2
  • 23
  • 43

1 Answers1

0

The most pythonic way of doing this that I could find is:

values = [1, 2, 3, 4, 5]
value = 3
replace = ['a', 'b', 'c']
def splice(values, value, replace):
    result = [replace if x == value else x for x in values]

Where you can just select which value to replace by and by what. This, however in a non-flat list. If you need it flat, this should be helpful (taken from here):

def flat_gen(x):
    def iselement(e):
        return not(isinstance(e, Iterable) and not isinstance(e, str))
    for el in x:
        if iselement(el):
            yield el
        else:
            for sub in flat_gen(el): yield sub

So if you use something like:

result_flat = list(flat_gen(result))

It should work as intended.

Márcio Coelho
  • 333
  • 3
  • 11