Why do I need to enumerate lists in order to replace indexed values?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096


Hi, can someone please explain why I need to use enumerate here?

I think the reason is that index values aren't automatically generated in lists, you need to manually generate them with enumerate. I wanted to confirm that my thought process is correct, and see if anyone could provide additional insight.

Please also let me know if there are any ways that I can improve the code.

Thanks.


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


#2

just using for in:

for wrd in b:
    print wrd

would give you read only values (values, not indexes) of b list.

You don't have to use enumerate, you can also use range():

for index in range(len(b)):
    print index

both will give you indexes. If i had to choice, i would pick enumerate.

but your thought process is right, so that is good :slight_smile:


#3

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