16. Using strings in lists in functions misunderstanding


#1

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

I used this code for this exercise and it works fine by printing "MichaelLieberman".

But if you change the result variable to this:

result = item + result

It prints out : "LiebermanMichael" (the thing is this usually shouldn't happen)

Why is this the case? Can anyone explain? Help is very much appreciated.


#2

The above operation is concatenating item to the left hand side of result, hence the words are shown in reverse.

y = "one"
y += "two"         # concatenate to right side
print y            # onetwo

y = "three" + y    # concatenate to left side
print y            # threeonetwo

#3

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