Study Guide

8.4.12 Librarian, Part 2 CodeHS Answers

8.4.12 Librarian, Part 2 CodeHS Answers

The most common answer is:

list=[]
for i in range (5):
name = input(“Name: “)
list.append(name.split()[-1])
list.sort()
print(list)

The script is aimed at collecting five names from the user, extracting the last name from each full name, sorting these last names, and then printing the sorted list.

To ensure full compatibility with Python syntax and to avoid using “list” as a variable name (since it’s a built-in type in Python), let’s adjust the quotation marks and use a more descriptive variable name:

last_names = []  # Using 'last_names' instead of 'list' to avoid overriding the built-in type

for i in range(5):
    full_name = input("Name: ")  # Collecting the full name from the user
    last_names.append(full_name.split()[-1])  # Extracting the last name and adding it to the list

last_names.sort()  # Sorting the list of last names alphabetically
print(last_names)  # Printing the sorted list

This script:

  • Initializes an empty list named last_names.
  • Prompts the user to enter a full name five times, each time extracting the last name (assuming the last name is the last word in the full name) by splitting the string and selecting the last element.
  • Sorts the last_names list in place using the .sort() method.
  • Prints the sorted list of last names.

This approach ensures that regardless of how many parts a name has, it consistently extracts and sorts the last word of each input as the last name.