Using strings in lists in functions


#1


prints backwards (LiebermanMichael instead of MichaelLiberman)


I was still expecting it to pick up Michael before Lieberman...why does it do it the other way around?


 n = ["Michael", "Lieberman"]

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

print join_strings(n)


#2

because you choice to insert lieberman before micheal:

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

print join_strings(n)

you store in result words[x] (lieberman) + result (micheal), you want to swap this:

result = result + words[x]

#3

I know, I can see what it does and how to fix it but I still don't get it! It seems illogical to me..

if result is an empty string to begin with, word[x] surely works to pick up the first word in the list, Michael, and add it to the empty string? only on the second iteration through the list would it pick up Lieberman... clearly not but i don't really understand why


#4

after the first iteration of the loop result will hold micheal, but then in the second iteration of the loop you update the result variable. what will be stored in result? words[x] (Lieberman) + what was already in results (micheal)

in the second iteration of the loop, you insert lieberman before micheal.


#5

ahhhhh, i get it now.

sorry for being dim!


#6

no need to apologize, getting to grip with some programming concepts can be difficult, it can sometime be counter intuitive.

Good you understand now, that is very important :slight_smile: Glad i could be of help :slight_smile:


#7

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