16. Using strings in lists in functions help


#1

n = ["Michael", "Lieberman"]
def join_strings(words):
result=""
for i in range(len(words)):
result += words[i]
return result

print join_strings(n)

I got a message saying "join_strings(['x', 'y', 'z', 'a']) returned 'x' instead of 'xyza'" and I'm a bit confused.


#2

Hi,

is

return result maybe indented to the same level result += words[i] is?

It's easier to loop through a list with for i in some_list:


#3

It is indented to the same level.

Did you mean to replace range(len(words)) with some_list because I tried that?


#4

The return statement needs to be outside of the loop, everytime a return statement is executed the function exits.

In your fuction you would have to replacefor i in range(len(words)) with for word in words because you want to loop throug words. You also would have to replace words[i] with word in this example. It's not necessary, but it's easier to read.


#5

Thank you it worked!