Using strings in lists in functions


#1

Hey guys!

I've been going through the python course in this site without coming across any notable difficulties, that is, until i reached the "Using strings in lists in functions" part in "Lists and Functions".

I've actually succeeded in completing the exercise, but it left me at the end with more questions than answers. Here are the three bits of code i tried:


n = ["Michael", "Lieberman"]

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

print join_strings(n)


n = ["Michael", "Lieberman"]

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

print join_strings(n)


n = ["Michael", "Lieberman"]

def join_strings(words):
result = ""
for i in words:
result += i
return result

print join_strings(n)


The first bit of code works perfectly fine, so no need to dwell on it too much. The real problem lays with the second and third bits of code, and more specifically, the second one.

I explain myself: When i use the second bit of code, it gives me the following error: "TypeError: list indices must be integers, not str" which means that the variable i takes the value of the content in the list instead of their indexes, which is, as far as i know, not the way it works :confused:
It is further proved in the third code, as it runs smoothly without giving any kind of error and gives the result that the exercise is asking for (concatenating the strings in the list).

Any help would be appreciated.

Thank you.


#2

well, the second approach gives you the values from the list directly, which you can see with a simple print statement:

n = ["Michael", "Lieberman"]

def join_strings(words):
    result = ""
    for i in words:
        print i
    return result

print join_strings(n)

where as range() gives you indexes, in which case you do need the square brackets to get the value from the list using indexes (produced by range)


#3

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