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

    
    
    list = ['cow','orange','mango']
    to_replace = 'orange'
    replace_with = ['banana','cream']
    

So I want that my list becomes like this after replacement

    
    
    list = ['cow','banana','cream','mango']
    

I am using this function:

    
    
    def replace_item(list, to_replace, replace_with):
        for n,i in enumerate(list):
          if i== to_replace:
             list[n]=replace_with
        return list
    

It outputs the list like this:

    
    
    ['cow', ['banana', 'cream'], 'mango']
    

So how do I modify this function to get the below output?

    
    
    list = ['cow','banana','cream','mango']
    

NOTE: I found an answer here: [Replacing list item with contents of another
list](http://stackoverflow.com/questions/14962931/replacing-list-item-with-
contents-of-another-list) 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.


Answer: This approach is fairly simple and has similar performance to @TadhgMcDonald-
Jensen's `iter_replace()` approach (3.6 µs for me):

    
    
    lst = ['cow','orange','mango']
    to_replace = 'orange'
    replace_with = ['banana','cream']
    
    def replace_item(lst, to_replace, replace_with):
        return sum((replace_with if i==to_replace else [i] for i in lst), [])
    
    print replace_item(lst, to_replace, replace_with)
    # ['cow', 'banana', 'cream', 'mango']
    

Here's something similar using itertools, but it is slower (5.3 µs):

    
    
    import itertools
    def replace_item(lst, to_replace, replace_with):
        return list(itertools.chain.from_iterable(
                replace_with if i==to_replace else [i] for i in lst
        ))
    

Or, here's a faster approach using a two-level list comprehension (1.8 µs):

    
    
    def replace_item(lst, to_replace, replace_with):
        return [j for i in lst for j in (replace_with if i==to_replace else [i])]
    

Or here's a simple, readable version that is fastest of all (1.2 µs):

    
    
    def replace_item(lst, to_replace, replace_with):
        result = []
        for i in lst:
            if i == to_replace:
                result.extend(replace_with)
            else:
                result.append(i)
        return result
    

Unlike some answers here, these will do multiple replacements if there are
multiple matching items. They are also more efficient than reversing the list
or repeatedly inserting values into an existing list (python rewrites the
remainder of the list each time you do that, but this only rewrites the list
once).

