10. Censor: question about for loop saving over original list



I have a question about the for loop saving over the original list index on the Censor exercise. I tried to get the list index to save over the original list index (if "index = word", save asterisks) and return the new list back.

However, I get the error: "Your function fails on censor("hey hey hey","hey"). It returns "hey hey hey" when it should return "*** *** ***".

I would expect that my for loop would have replaced any "index = word" items with asterisks, and returned this as the new list. I am not sure why it did not save over the old list.

def censor (text, word):
    a = text.split()
    for i in a:
        if i == word:
            i = "*" * len(word)
    return " ".join(a)


i is just a read only version of items from your list

If you want to manipulate the list, use range or enumerate to get indexes so you can replace items in the list


Thanks that was helpful! I got it to work with enumerate.

def censor (text, word):
    a = text.split()
    for index, item in enumerate(a):
        if item == word:
            a[index] = "*" * len(word)
    return " ".join(a)

print(censor("hey hey hey", "hey"))