2

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.

El_1988
  • 339
  • 3
  • 13

2 Answers2

2

Try this:

List[1:3] = [["banana", "cream"]]

The reason this isnt working is because when you are writing: List[1:3] = ["banana", "cream"] you are replacing a list with a list. In other words you are changing ["orange", "apple"] to ["banana", "cream"].

When doing this: List[1:3] = [["banana", "cream"]] you replace a list with a list in a list, replacing ["orange", "apple"] with [["banana","cream"]], thereby replacing "orange", "apple" with ["banana", "cream"]

Sriram A.
  • 78
  • 6
1
def replace_item(lst, to_replace, replace_with):
    for n,i in enumerate(lst):
      if i in to_replace and lst[n+1] in to_replace:
         lst[n]=replace_with
         lst[n+1] = ""
    return [item for item in lst if item]

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

print (replace_item(lst, to_replace, replace_with))

Output:

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

First, don't call your var the same name as object type. That is a bad idea that can lead to code confusion/bugs etc.

In your function, the problem was essentially that the == operator between a string (i) and a list (lst) will never say True regardless the rest. Plus, the content in string in the list is not the same as in your string. So you use in instead of ==.

After this, if you don't want to have a duplicate and wish to replace adjacent 'orange', 'apple' by a single ['banana','cream'], you need to check lst[n+1] when iterating.

Then you replace lst[n], set lst[n+1] to nothing and return a list purged from nothing elements using list comprehension.

Synthase
  • 5,849
  • 2
  • 12
  • 34
  • thanks very much, for some reason in my loop this gives me "index out of range" error, not sure where the error is from but the solution above worked – El_1988 Jan 12 '21 at 05:17
  • Good! Think about accepting the answer if that helped ;) – Synthase Jan 12 '21 at 05:51