Open In App

Python Program to Sort A List Of Names By Last Name

Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of names, the task is to write a Python program to sort the list of names by their last name.

Examples:

Input: [‘John Wick’, ‘Jason Voorhees’]

Output: [‘Jason Voorhees’, ‘John Wick’]

Explanation: V in Voorhees of Jason Voorhees is less than W in Wick of John Wick. 

Input: [‘Freddy Krueger’, ‘Keyser Söze’,’Mohinder Singh Pandher’]

Output: [‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’]

Explanation: K< P < S

Method #1: Using sorted() method on a converted 2D List.

Convert the list of names into a 2D list of names, in which the first index refers to the first names and the last index refers to the last name. Apply sorted() method with key as the last index of each element in the 2D list.

Python3




# explicit function sort names
# by their surnames
def sortSur(nameList):
    l2 = []
 
    # create 2d list of names
    for ele in nameList:
        l2.append(ele.split())
    nameList = []
 
    # sort by last name
    for ele in sorted(l2, key=lambda x: x[-1]):
        nameList.append(' '.join(ele))
 
    # return sorted list
    return nameList
 
 
# Driver Code
 
# assign list of names
nameList = ['John Wick', 'Jason Voorhees',
            'Freddy Krueger', 'Keyser Soze',
            'Mohinder Singh Pandher']
 
# display original list
print('\nList of Names:\n', nameList)
print('\nAfter sorting:\n', sortSur(nameList))


Output:

List of Names: [‘John Wick’, ‘Jason Voorhees’, ‘Freddy Krueger’, ‘Keyser Soze’, ‘Mohinder Singh Pandher’] After sorting: [‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’, ‘Jason Voorhees’, ‘John Wick’]

Time Complexity: O(n)

Space Complexity: O(n)

Method #2: Using sort() method + lambda

Use sort() method on the given list of names with key as lambda x: x.split()[-1]) which represents the last string in each element of the list.

Python3




# explicit function sort names
# by their surnames
def sortSur(nameList):
     
    # sort list by last name
    nameList.sort(key=lambda x: x.split()[-1])
     
    # return sorted list
    return nameList
 
 
# Driver Code
 
# assign list of names
nameList = ['John Wick', 'Jason Voorhees',
            'Freddy Krueger', 'Keyser Soze',
            'Mohinder Singh Pandher']
 
# display original list
print('\nList of Names:\n', nameList)
print('\nAfter sorting:\n', sortSur(nameList))


Output:

List of Names: [‘John Wick’, ‘Jason Voorhees’, ‘Freddy Krueger’, ‘Keyser Soze’, ‘Mohinder Singh Pandher’] After sorting: [‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’, ‘Jason Voorhees’, ‘John Wick’]

Time Complexity: O(nlogn) -> Python in-built sort function takes O(nlogn)

Space Complexity: O(n)

Method #3: Using itemgetter

Here is an example of how to use the itemgetter method from the operator module to sort the list of names by their last names:

itemgetter is a fast and memory-efficient way to sort a list based on one or multiple attributes of the elements in the list. In this case, we are using a lambda function to return the last name of each name in the list, and using itemgetter to sort the list based on the last names.

Time complexity: O(nlogn), as the sorting is performed by the built-in sorted function which takes O(nlogn) time.

Space complexity: O(n), as we are storing the sorted list in memory.

Python3




from operator import itemgetter
 
def sort_by_last_name(name_list):
    # sort the list of names by the last name using itemgetter
    name_list = [x.split() for x in name_list]
    sorted_list = [" ".join(i)  for i in sorted(name_list, key=itemgetter(1))]
    return sorted_list
 
# Example usage
name_list = ['John Wick', 'Jason Voorhees', 'Freddy Krueger', 'Keyser Soze', 'Mohinder Singh Pandher']
print(sort_by_last_name(name_list))
# Output: ['Freddy Krueger', 'Mohinder Singh Pandher', 'Keyser Soze', 'Jason Voorhees', 'John Wick']


Output

['Freddy Krueger', 'Mohinder Singh Pandher', 'Keyser Soze', 'Jason Voorhees', 'John Wick']


Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads