Boggled with censor difference


#1



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

I dont get the difference between this:


def censor(text, word):
    ltext = text.split()
    print len(ltext)
    for i in range(0,len(ltext)):
        if ltext[i] == word:
            ltext[i] = "*" * len(word)
    return " ".join(ltext)  .

and this:

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

Please help me understand this well. Thanks!


#2

Your range(0, len(ltext)) returns a list with numbers starting from 0 to len(ltext).
Check docs.

text = "a big black wolf"
ltext = text.split()
print range(0, len(ltext))
# => [0, 1, 2, 3]

You can use these numbers to iterate through your list, they can be indices of your list elements.

for i in range(0, len(ltext)):
    print i, ltext[i]
"""
=> 0 a
=> 1 big
=> 2 black
=> 3 wolf
"""

Here, your i is an element of you list. This syntax looks like:

for element in list:
    print element

You can read this element, but you don't know what is it's index in list.
So you can't use it as index of list, it will give you an error:

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
  File "<stdin>", line 5, in censor
TypeError: list indices must be integers, not str

because your list elements are strings.


#3

Okey I think I got it. Thanks a lot for your help!