Replacing an item in list with items of another list without using dictionaries
<p>I am developing a function in python. Here is my content:</p>

<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>

<p>So I want that my list becomes like this after replacement</p>

<pre><code>list = ['cow','banana','cream','mango']
</code></pre>

<p>I am using this function:</p>

<pre><code>def replace_item(list, to_replace, replace_with):
    for n,i in enumerate(list):
      if i== to_replace:
         list[n]=replace_with
    return list
</code></pre>

<p>It outputs the list like this:</p>

<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>

<p>So how do I modify this function to get the below output?</p>

<pre><code>list = ['cow','banana','cream','mango']
</code></pre>

<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>

<p>Modifying a list whilst iterating through it is usually problematic because the indices shift around.  I recommend to abandon the approach of using a for-loop.</p>

<p>This is one of the few cases where a <code>while</code> loop can be clearer and simpler than a <code>for</code> loop:</p>

<pre><code>&gt;&gt;&gt; list_ = ['cow','orange','mango']
&gt;&gt;&gt; to_replace = 'orange'
&gt;&gt;&gt; replace_with = ['banana','cream']
&gt;&gt;&gt; while True:
...     try:
...         i = list_.index(to_replace)
...     except ValueError:
...         break
...     else:
...         list_[i:i+1] = replace_with
...         
&gt;&gt;&gt; list_
['cow', 'banana', 'cream', 'mango']
</code></pre>

python list