16. Using strings in lists in functions


#1



16. Using strings in lists in functions

I get this error - Traceback (most recent call last):
File "python", line 8, in
File "python", line 6, in join_strings
MemoryError


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

print join_strings(n)


#2

append() you use when you want to append an item to a list.

Also, result should be an empty string:

result = ""

you should add the word to the string, i holds the words in the for loop:

result = result + i

You can see i hold the words with:

for i in words:
   print i

#3

I'm still confused. I changed the words.append(result) but I still get an error.


#4

Can you post an updated version of your code?


#5

n = ["Michael", "Lieberman"]

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

print join_strings(n)

It also is telling me that "words is not defined"


#6

Take a close look at the indention of your code, the for loop is not inside the function, and the function doesn't return anything


#7

Now I it just returns none. No error though.


#8

Never mind. I just forgot to return result. Thanks!


#9

The following worked for me , however i was wondering why the .append(words[i]) doesn't work.

def join_strings(words):
        result = ""
        for i in range(len(words)):
            result = result + words[i]
            #result.append(words[i])
            #this doesn't work gives the following error Traceback (most recent call last):
            #  File "python", line 9, in <module>
            #  File "python", line 7, in join_strings
            #AttributeError: 'str' object has no attribute 'append'
        return result
    print join_strings(n)

Does anyone have an idea why the commented version won't work?


#10

because append is a function designed to append items to a list, result is a string, not a list.


#11

Tnx that explaines a lot!


#12

in 2.7 you can do this:
print ' '.join(n)

but in 3.4 you will get a "SyntaxError: invalid syntax" error message


#13

the problem why this won't work is because of print, print in python 2.7:

print "i am printed"

in 3.4 you need brackets:

print("i am printed")

knowing we can solve your problem:

print(' '.join(n))

#14

Okay, that is the way to do it. Thanks!