STRING METHODS Splitting Strings II


I’m confused about the difference between .append() and += code.

Second part of this lecture ask to “Create another list called author_last_names that only contains the last names of the poets in the provided string.”

And here is code I wrote.

authors = "Audre Lorde,Gabriela Mistral,Jean Toomer,An Qi,Walt Whitman,Shel Silverstein,Carmen Boullosa,Kamala Suraiyya,Langston Hughes,Adrienne Rich,Nikki Giovanni"

author_names = authors.split(',')

author_last_names = []
for name in author_names:
  last_name = name.split ()[-1]
  author_last_names += last_name
print (author_last_names)

And I got each letter of each person’s last name as a single string.

[‘L’, ‘o’, ‘r’, ‘d’, ‘e’, ‘M’, ‘i’, ‘s’, ‘t’, ‘r’, ‘a’, ‘l’, ‘T’, ‘o’, ‘o’, ‘m’, ‘e’, ‘r’, ‘Q’, ‘i’, ‘W’, ‘h’, ‘i’, ‘t’, ‘m’, ‘a’, ‘n’, ‘S’, ‘i’, ‘l’, ‘v’, ‘e’, ‘r’, ‘s’, ‘t’, ‘e’, ‘i’, ‘n’, ‘B’, ‘o’, ‘u’, ‘l’, ‘l’, ‘o’, ‘s’, ‘a’, ‘S’, ‘u’, ‘r’, ‘a’, ‘i’, ‘y’, ‘y’, ‘a’, ‘H’, ‘u’, ‘g’, ‘h’, ‘e’, ‘s’, ‘R’, ‘i’, ‘c’, ‘h’, ‘G’, ‘i’, ‘o’, ‘v’, ‘a’, ‘n’, ‘n’, ‘i’]

When I changed " author_last_names += last_name" to “author_last_names.append(last_name)” I was able to get the correct answer but I don’t understand why the first way didn’t work. last _name was a single string, why did each letter of the name become a single string? Can someone help?



This was a fun one. I’ve been digging through the Python documentation to see if I could find an explanation as to why you’re getting that behaviour, but I can’t find one. So, I’ll see if I can explain it.

Both the list type and the string type in Python are iterable.

If we concatenate two lists, we get back a single list containing all the items of both lists:

list1 = [1,2,3]
list2 = [4,5,6]

print(list1 + list2) # output: [1,2,3,4,5,6]

Similarly, if we do the same with two strings:

string1 = "abcdef"
string2 = "ghijkl"

print(string1 + string2) # output: abcdefghijkl

We also know, with the += operator, that the following is true:

a += b === a = a + b

What Python is doing, when you are doing author_last_names += last_name, is taking the first iterable - author_last_names - and adding every item from the second iterable - last_name - into it.

It’s essentially the same as if you were to convert your string into a list…

name = list("Lorde")
print(name) # output: ['L', 'o', 'r', 'd', 'e']

…and then use the known behaviour of list + list. Python sticks the two sequences together.

If you wanted to stick with using +=, rather than list.append(), it gets a bit convoluted:

author_last_names += ['%s' % last_name]

where I’ve used printf formatting to create a single item list, and replace the placeholder with the value of last_name. It’s not elegant, at all. (There may be another way to do this, but this is the one that came to me now.)

Hopefully that explains it… but let us know if you’re still stuck. :slight_smile:

Also, welcome to the forums! :slight_smile: