Using strings in lists in functions: How does it work?


#1



https://www.codecademy.com/en/courses/python-beginner-nzzVa/3/5?curriculum_id=4f89dab3d788890003000096#


My question is simply for line 6, that reads: "result = result + word". I would like an explanation of how it works, because I'm a bit confused.


n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
    result = ""
    for word in words:
        result = result + word
    return result
    
print join_strings(n)


#2

This is the process of concatenation and reassignment.

A string is an immutable object so we cannot change the string directly, but we can replace the string with something new. It is possible to join two strings so long as we assign it to another variable, and as above, that variable can be the same one we had to begin with.

result = result + word

We can rewrite this with the compound operator that concatenates and assigns in single stroke. Just as above, the concatenation takes place first to construct the temporary new string, then the assignment.

result += word

#3

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