Replace item with list in python
In python, what's the best way to replace an item in a list with items from another list?
For example, I have:
a = [ 1, 'replace_this', 4 ]
I want to replace replace_this
with [2, 3]
. After replacement, it should be:
a = [ 1, 2, 3, 4 ]
Update
Of course this can be done with slicing (I wish I had written it in the question), but the problem is that it is possible that you have more than one value replace_this
in the list. In this case, you need to do the replacement in a loop and it becomes sub-optimal.
I think it would be better to use it itertools.chain
, but I'm not sure.
source to share
You can just slice:
>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]
And as @mgilson points out - if you don't know the position of the element being replaced, you can use a.index
to find it ... (see his comment)
update related to using unsharp
Using itertools.chain
, make sure to replacements
iterate:
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]
source to share
I would go with a generator to replace items and the other generator is flatten . Assuming you have a working generator flatten
like the one 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)))
source to share