Practice makes perfect: Censor; Why is this code incorrect?


Not sure what I'm doing wrong here. What I assume to be the issue is that objects in a list cannot be replaced by reassignment using the variable said object was stored under in a for loop. Is this true? If so, would anyone happen to have a link to further information on the topic?

Note: I have already solved the exercise with another code, but I'm trying to understand why this one isn't working.

Like in the exercise, this function is supposed to take a string of text, and a word that is desired to be censored from said list

def censor(text, word):
    text = text.split(' ')
    for item in text:
        if item == word:
            item = '*' * len(word)
    return ' '.join(text)


Change to item is not updated in text.

text[text.index(item)] = '*' * len(word)   # (corrected)


Thought so. Thank you.

Is there any particular reason why that is, or is it kind of a "that's just how python works" kind of thing?


item is not technically in the list, but a copy taken from the list. See my edit above.


will return the index, which we can then use to replace the content at that index.

We can also use enumerate which has both index and item parameters.

for i, x in enumerate(text):
    if x == word:
        text[i] = ...


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.