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