Python Program to Sort A List Of Names By Last Name
Last Updated :
15 Feb, 2023
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']
Similar Reads
Python program to sort a list of tuples alphabetically Given a list of tuples, write a Python program to sort the tuples alphabetically by the first item of each tuple. Examples: Input: [("Amana", 28), ("Zenat", 30), ("Abhishek", 29), ("Nikhil", 21), ("B", "C")] Output: [('Amana', 28), ('Abhishek', 29), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)] Input:
3 min read
Python program to Sort a List of Strings by the Number of Unique Characters Given a list of strings. The task is to sort the list of strings by the number of unique characters. Examples: Input : test_list = ['gfg', 'best', 'for', 'geeks'], Output : ['gfg', 'for', 'best', 'geeks'] Explanation : 2, 3, 4, 4 are unique elements in lists. Input : test_list = ['gfg', 'for', 'geek
6 min read
Python Program to Sort Words in Alphabetical Order The task is to write a program that takes a list of words as input and sorts them in alphabetical order. The program should display the sorted list of words, ensuring that the sorting is case-insensitive. To sort words in alphabetical order in Python, we can use the sorted() function or the sort() m
2 min read
Python - Sort list according to other list order Sorting a list based on the order defined by another list is a common requirement in Python, especially in scenarios involving custom sorting logic. This ensures that elements in the first list appear in the exact order specified in the second list. Python provides various methods to accomplish this
2 min read
Python - Sort list of lists by the size of sublists The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.Using sorted() with len() This me
3 min read
Python | Sort given list of dictionaries by date Given a list of dictionary, the task is to sort the dictionary by date. Let's see a few methods to solve the task. Method #1: Using naive approach Python3 # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'a
2 min read