16. Using Strings in Lists in Functions


#1

I've been really struggling with understanding this one. it seems that using one for-loop method creates an error, and using the other method doesn't, and I was wondering if this could be explained to me?

Example one:

n = ["Michael", "Lieberman"]

def join_strings(words):
    result = ""
    for w in words:
        result = result + words[w]
    return result

print join_strings(n)

This particular code creates the error:

Traceback (most recent call last):
File "python", line 10, in
File "python", line 6, in join_strings
TypeError: list indices must be integers, not str

Example two:

n = ["Michael", "Lieberman"]

def join_strings(words):
    result = ""
    for w in range(len(words)):
        result = result + words[w]
    return result

print join_strings(n)

This one works out, works fine. I've been trying to understand why the first block creates an error and the second block doesn't. The exercise states that either method will be fine to create the looping.

Am i missing something?


#2

first code, this line:

result = result + words[w]

is wrong, it should be:

result = result + w

Why? Well, if you use a for .. in loop, will simple hold the word, and you can just add it to the string with a + w, you can see w holds the word by doing:

for w in words:
   print w
   result = result + words[w]

now, in range you will get the index:

for w in range(len(words)):
    print w
    result = result + words[w]

then you can use the bracket notation to access the word at that particular index. Hope this helps


#3

I think I get it.

So in the former, since the range(len()) isn't there, it can't perform the indexing with the hard brackets, and with the latter the range(len()) allows for the data to be indexed? I understand.

That's what the exercise means when it says that with range(len()) you can control more things about the looping and with the other, more direct method you can't?

Still learning...


#4

i think you indeed get it, using the index gives you more control, if you use range, you could updated the variable:

for w in range(len(words)):
        words[w] = "updated"
    return result

where you can't do this with for w in words