3

In python, what is the best way to replace an element in a list with the elements from another list?

For example, I have:

a = [ 1, 'replace_this', 4 ]

I want to replace replace_this with [2, 3]. After replacing it must be:

a = [ 1, 2, 3, 4 ]

Update

Of course, it is possible to do with slicing (I'm sorry that I didn't write it in the question), but the problem is that it is possible that you have more than one replace_this value in the list. In this case you need to do the replacement in a loop and this becomes unoptimal.

I think that it would be better to use itertools.chain, but I'm not sure.

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144

2 Answers2

12

You can just use slicing:

>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]

And as @mgilson points out - if you don't happen to know the position of the element to replace, then you can use a.index to find it... (see his comment)

update related to not using slicing

Using itertools.chain, making sure that replacements has iterables:

from itertools import chain

replacements = {
    'replace_this': [2, 3],
    4: [7, 8, 9]
}

a = [ 1, 'replace_this', 4 ]
print list(chain.from_iterable(replacements.get(el, [el]) for el in a))
# [1, 2, 3, 7, 8, 9]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

I would go with a generator to replace the elements, and another generator to flatten it. Assuming you have a working flatten generator, such that in the link provided:

def replace(iterable, replacements):
    for element in iterable:
        try:
            yield replacements[element]
        except KeyError:
            yield element

replac_dict = {
    'replace_this': [2, 3],
    1: [-10, -9, -8]
}
flatten(replace(a, replac_dict))
# Or if you want a list
#list(flatten(replace(a, replac_dict)))
Community
  • 1
  • 1
themiurgo
  • 1,550
  • 2
  • 13
  • 16