Goal:
In this lesson, the second task requests that you take the list of author names and convert it to just a list of last names. Here I will break down and explain each step in that process to help those struggling with this task.
Note that this explanation spoils the solution and as such if you wish to solve it yourself you may not want to read this until you are satisfied having done it yourself. As such each code block is spoilered out and can be clicked to see the code.
Explanation
In order to break down how to solve this, we should identify the format our data is already in then what steps are necessary to get it into what we want. After the first task, you should have a list that looks like
['Audre Lorde', 'Gabriela Mistral', 'Jean Toomer', 'An Qi', 'Walt Whitman', 'Shel Silverstein', 'Carmen Boullosa', 'Kamala Suraiyya', 'Langston Hughes', 'Adrienne Rich', 'Nikki Giovanni']
It is a list of strings each containing a first and last name with a space in between. So we want to isolate the last names. There are other solutions but I will use the one hinted at. The steps involved:
- Break the first and last name apart using
.split()
- Isolate the last name using a negative index
- Create a new list of last names using
.append()
So lets take the first step. We are already familiar with using .split()
to break strings apart. This time we want to run it once on each item in the list, so we will use a for
statement. In order to split the first and last name, the dividing character is a space ' '
, but this is the default value for split so we can leave it without any parameters. This is what our code will look like so far:
for name in author_names:
name.split()
This won’t work as is since we aren’t actually putting that split name anywhere, this will be addressed in step 3.
On to step two. In each iteration of the loop name.split()
will spit out a list that looks like this ['firstname', 'lastname']
. We don’t need to use the first name so we can use indexing to select the lastname. This can be done utilizing either [1]
or [-1]
. The advantage of [-1]
is that if these names also had a middle name, or additional family names, only the last would be selected. Since name.split()
returns the split list, we can add [-1]
directly to it to instead return the chosen index item. Taking our return from ['firstname', 'lastname']
to just 'lastname'
. Note that we are not indexing the string itself, which would return a single character but are instead indexing the list of two names.
Our code looks like this now:
for name in author_names:
name.split()[-1]
Finally we need to send the names into a new list. This can be done by creating an empty list outside the for
loop (so it isn’t rewritten each time) and using .append()
as below:
author_last_names = []
for name in author_names:
author_last_names.append(name.split()[-1])
I hope you’ve found this explanation useful. Please discuss below and ask any followup questions.