Iteration Help


Would like some further clarification on these two iteration methods:

for item in list:
print item

for i in range(len(list)):
print list[i]

I can get my code for this exercise to work with the first option, but not the second. Is this because the second is expecting integers instead of strings?

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

This is the error:

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


range() will give you a list of integers, this list of integers match the indexes from your words list. So then you can do result[x] to use the index to retrieve items from list


Thank you that helped a bit, though I could not pass the list to result.. Instead I passed the list to the variable (words), and added it to result:

for x in range(len(words)):
result = result + words[x]
return result

I understand now that range is just creating indexes for the strings. But I have one last question... Is len() storing the length of the string so Python knows where the next index is supposed to begin?

Thank you for your help!


oops, my mistake. The fact that you managed to correct it means you understand :slight_smile:

yea, range() can have 3 values:

range(start, stop, step)

if you provide one value, it will be stop, start will be default (0) and step (1, +1)

you could check documtation on range


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