Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Sort names by last name using a lambda key

Use sorted with a lambda key that extracts the last name to sort a list of full names.

Python practice15 minFunctions as Objects (Lambda, Map/Filter)IntermediateLast updated March 20, 2026

Problem statement

Given a list of names where each name is a string (may contain multiple words or just one), return a new list sorted by last name. The last name is defined as the last whitespace-separated token in the string after stripping leading/trailing whitespace. Comparison should be case-insensitive but the returned names must be the original strings (preserve original casing and spacing). Use a lambda key with sorted.

Task

Sort a list of full names by last name using a lambda as the key function. Handle single-word names and preserve original spacing in the output.

Examples

Sort by last name

Input

sort_names_by_last(['Ada Lovelace', 'Alan Turing', 'Grace Hopper'])

Output

['Grace Hopper', 'Ada Lovelace', 'Alan Turing']

Last names: Hopper, Lovelace, Turing -> Hopper, Lovelace, Turing

Input format

A list of name strings, e.g. ['John Doe', 'Ada Lovelace'].

Output format

A new list of the original name strings sorted by last name.

Constraints

Names may be single-word (treated as last name). Comparison is case-insensitive.

Samples

Sample 1

Input

sort_names_by_last(['Plato', 'Socrates', 'Aristotle'])

Output

['Aristotle', 'Plato', 'Socrates']

Single-word names are sorted alphabetically by that 'last' word.