-2
def replace(L, old_obj, new_obj):
    L=[]
    for i in enumerate(L):
        if i ==old_obj:
            L.replace(old_obj, new_obj)
    return

I can't figure out what to do to make this code work. Am I missing something important that would allow this code to change? I want to make a list in L, then have a new object replace one in the list. for example L=[1,2,1,2,3]. replace(L, 2, 'a'). L=[1,'a',1,'a',3]

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58

1 Answers1

1

I think the first line of your function:

L=[]

is the first problem you're running into, and one that will mask the other errors here. Python isn't either call-by-value or call-by-reference - it's call-by-object-reference which is subtly (but importantly) different. Even though you're passing in the L object as the first argument of your function, L=[] doesn't change that object. It creates a new empty list object and assigns the name L to that object. After that moment, whatever you happen to do to L will be lost forever as soon as the function returns. Even if you got the rest of your function working, you'd never know because the fruits of your labor would be lost.

I'd suggest one of two approaches here:

1: Mutate the L object in place.

def mutate_list(L, old_obj, new_obj):
    for i, value in enumerate(L):
        if value == old_obj:
            L[i] = new_obj

Better in my opinion is:

  1. Build and return a new list object.
def return_new_list(L, old_obj, new_obj):
    new_list = []
    for value in L:
        if value == old_obj:
            new_list.append(new_obj)
        else:
            new_list.append(value)
    return new_list

Once you become really comfortable with Python, you'd probably write that more like:

new_list = [value if value != old_obj else new_obj for value in L]

...but that's for another day.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65