I am trying to replace elements in a list with a list containig said elements, for example:
list = ['cow','orange','apple','mango']
to_replace = 'orange', 'apple'
replace_with = ['banana','cream']
Desired output:
['cow', ['banana', 'cream'], 'mango']
I've read the answers in this question 1 and tried the function mentioned there:
def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
but it does nothing. I also tried a basic equality functions:
list[1:3] = ['banana','cream']
However neither work. Is there a function to accomplish this? In my actual problem which is a loop, list[1:3]
is an iterator, i.e. list[i:i+2]
. I am not sure if this makes a difference. The items to be replaced will always be sequential.