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.

2
  • And what have you tried? Commented Feb 6, 2013 at 14:19
  • I've updated with an example of using a replacement dictionary and chain Commented Feb 6, 2013 at 14:51

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

+1 -- And you can get the 1:2 via i = a.index('replace_this'); a[i:i+1] = [2,3]
This solution is really beautiful! Thank you very much for it
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)))

2 Comments

The problem is if you have nested lists that will not work. But anyway, +1
You didn't mention you had nested lists. And, in fact, also the other solution does not work with nested lists.

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.