Using strings in list and functions


#1



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


Oops, try again. join_strings(['x', 'y', 'z', 'a']) returned 'MichaelLieberman' instead of 'xyza'


I'm honestly not very sure why its not right? It says to add both strings together without any spaces?


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


print join_strings(n)


#2

lets add the the test case from the exercise:

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


print join_strings(n)
print join_string(['x', 'y', 'z', 'a']))

The second function call should print xyza, it doesn't. A function that works for a single list is not very effective

How could we make the function work for any lists supplied as argument on function call? Hint: function parameter


#3

You mean instead of using for words in n: , I should use for i in range(len(list)):


#4

list is a reserved word in python, and i don't see you use list anywhere in your code

its important to understand that arguments at function call get passed into the function parameters (words), so to make your function work for any list supplied as argument on function call you need to loop over the function parameter


#5

So here's what I've come up with

n = ["Michael", "Lieberman"]

Add your function here

def join_strings(words):
result = ""
for w in range(len(words)):
result = result + w
return result

print join_strings(n)

I've attempted to loop over the function parameter..


#6

not sure why you included range(), its possible but then you have to remember range() gives you indexes not values from the list

you do now look over the function parameter, that is good :slight_smile:


#7

Should I then include len to calculate the length?, it doesn't seem necessary as i'm only working with a list consisting of 2 strings..

If this is the case I probably got confused with how the first example shows 2 ways of iterating over a list. And the only answer can be in the first example, which is alot more simple ..


#8

yes, there are two ways to list over a list:

for each_item in your_list:

which will give you the items/values of the list, or:

for index in range(len(your_list)):

which gives you indexes, indexes can be useful if you want to manipulate the list


#9

I changed the code back to using for each_item in your_list: and it worked.
The only difference is the words is switched with w, now that I understand the concept, thank you very much. :joy:

n = ["Michael", "Lieberman"]

Add your function here

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

print join_strings(n)


#10