16. Using strings in lists in functions



Hi, I can do this exercise just fine without range(), however could someone please explain why range() here is not working?

Traceback (most recent call last):
File "python", line 9, in
File "python", line 6, in join_strings
TypeError: cannot concatenate 'str' and 'int' objects

n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
    result = ""
    for word in range(len(words)):
        result += word
    return result

print join_strings(n)


Because you use the range-function, your variable word will have values like: 0,1,2 upto len(words)-1

result is a string and you try to concatenate it with a int-value (word)

you have to write:
result += words[word], since word is only an index for the list words


Great, thanks much for the explanation. Unfortunately the lesson itself still offers range() as a possible solution (a bit misleading).


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