How to sort names by surname

Viewed 121

I would like to sort the below list of full names by their surname (a-z). How could we do that with a sorted function and a lambda? Is there a better way?

people = ['Fred Johnson', 'Tom E. Roth', 'Jazz Ishingham', 'Fred Kazai', 'Robert Wass', 'You  Mee']
2 Answers

I would like to supplement the other answers: in the case when 'people' list elements can have trailing spaces, we can remove them this way:

sorted(people, key=lambda el: el.rstrip().split(' ')[-1])

Also we could use re module this way:

import re
sorter = lambda el: re.search(r'(\w+)(?:\s*)$', el).group(1)
sorted(people, key=sorter)

Here we take only a surname, without any trailing spaces.

Related