Elisha512 Elisha512 - 4 months ago 10
Python Question

Replacing an item in list with items of another list without using dictionaries

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:
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
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.


First off, never use python built-in names and keywords as your variable names. (change the list to ls)

You don't need loop, find the index then chain the slices:

In [107]: from itertools import chain    
In [108]: ls = ['cow','orange','mango']
In [109]: to_replace = 'orange'
In [110]: replace_with = ['banana','cream']
In [112]: idx = ls.index(to_replace)  
In [116]: list(chain(ls[:idx], replace_with, ls[idx+1:]))
Out[116]: ['cow', 'banana', 'cream', 'mango']

In pyhton 3.5+ you can use in-place unpacking:

[*ls[:idx], *replace_with, *ls[idx+1:]]