Why when adding a string to an empty list do I get each letter split up?


#1



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


So I was just curious, why the following code gives me a list where each letter is a new item. If result is an empy list and I add + words[i] surely it should be results = ['Michael'] since words[i] has the the string of michael if [i] was 0?


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


#2

There's a difference between concatenating to and appending to.

Right now you're concatenating a sequence to your list.

>>> a = []
>>> a += 'hello'
>>> a
['h', 'e', 'l', 'l', 'o']

#3

Thanks for the reply,

so is there no way to add the string to the empty list. I know how to make the word using .join() but I just wanted to know why this method gives an undesired output


#4

Same way as you'd add any other value to a list.
How do you add 5 to a list?


#5

m = []

m.append(1)

like this?

Also another question if instead I made result = " " is that essentially saying there will be a string added to this? and anything added will go between the quotation mark?


#6

Is there something wrong with my code? result += apparently is invalid, that's what I see as an error message in the console

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

print join_strings(n)


#7

You forgot a bracket and colon after len(words)


#8

Thanks, I kind of just saw that immediately I pressed the post button. I should pay more attention to detail. Thanks once again


#9

That's assignment.
There's no "essentially saying", everything happens in certain exact ways, whatever way it was programmed to do, and if you need to know for sure what something does, you have to look it up, in documentation or even source code.

When you use operators, it is the values themselves that define what happens. strings and lists have their own version of add, because adding means different things when the data types change.