How do I print only the last names on CodeHS 8.4.12: Librarian, Part 2?

This is what I'm supposed to do: In the Librarian exercise, you asked the user for five last names, and you then printed a list of those names in sorted order.

In this exercise, you will ask the user for five full names. You should still print a list of last names in sorted order.

Each time you retrieve a name from the user, you should use the split method and the right index to extract just the last name. You can then add the last name to the list of last names that you will ultimately sort and print.

Here’s what an example run of your program might look like:

Name: Maya Angelou
Name: Chimamanda Ngozi Adichie
Name: Tobias Wolff
Name: Sherman Alexie
Name: Aziz Ansari
['Adichie', 'Alexie', 'Angelou', 'Ansari', 'Wolff']

This is my code right now:

name_1 = input("Name: ")
name_1.split()
name_2 = input("Name: ")
name_2.split()
name_3 = input("Name: ")
name_3.split()
name_4 = input("Name: ")
name_4.split()
name_5 = input("Name: ")
name_5.split()
my_list = [name_1[-1], name_2[-1], name_3[-1], name_4[-1], name_5[-1]]
my_list.sort()
print my_list

My code right now prints only the last letter, not the last word. How do I get my code to print the last word?

6

2 Answers

Your problem is doing some_string[-1] on a string which takes only the last letter of that string. Solution is to use some_string.split() on your string to split it by space into a list of values and then take the last element of that list with some_list[-1].

names_list = []
for i in range(0, 5): names_list.append(input("Name: "))
sorted_last_names = sorted([name.split()[-1] for name in names_list])
print(sorted_last_names)
0

This is easier than the answer above. For me, it's more clear this way.

name_list = []
for i in range (5): input_name = input("Name: ") name_list.append(input_name.split()[-1])
name_list.sort()
print(name_list)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like