Splitting Strings II - Need help understanding question 2 solution

Hi,

On the Splitting Strings II section, I need help deciphering how the solution provided for question 2 works.

Here is the link to the exercise:
https://www.codecademy.com/courses/learn-python-3/lessons/string-methods/exercises/splitting-strings-ii

The challenge is to create a list with only the last name of the author from the authors’ string.

I am confused how the for loop action of appending the character in the string, split by a space, and looking at the index -1, brings up only the last name of the author in the string.

Can someone please help me breakdown what is happening in the for loop, specifically in the action part of the loop?

System solution:

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

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

Thank you!

1 Like

Actually the action

split() #returns a list 

say,. name = Audre Lorde

so the split() function will create a list virtually [‘Audre’, ‘Lorde’]

Now, the index [-1] applied to this list, which pointing out ‘Lorde’

The append() then puts that value given by (name.split() [-1]) to the author_last_names.

You left out the first step:

author_names = authors.split(',')

… which gives a list of strings like this: ["Audre Lorde", "Gabriela Mistral", "Jean Toomer", ...]

After that, you enter the ‘for’ loop, where the first item in the loop is name = "Audre Lorde" , so that name.split() is ["Audre", "Lorde"], and the item at the [-1] index position of that is "Lorde".

2 Likes