Python Program to Sort A List Of Names By Last Name


In this article, we will learn a python program to sort a list of names by last name.

Methods Used

  • Using lambda and sorted() functions

  • Using lambda and sort() functions

Example

Assume we have taken an input list containing string elements. We will now sort the list elements in ascending order of the last names alphabetically using the above methods.

Input

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']

Output

Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

The last names of input list elements are tendulkar, raina, pandya i.e t, r, p(first char order). We sort them in ascending order of the last names alphabetically which means p, r, t (p<r<t).

Method 1: Using lambda and sorted() functions

Lambda Function

Lambda Function, often known as an 'Anonymous Function,' is the same as a normal Python function except that it can be defined without a name. The def keyword is used to define normal functions, while the lambda keyword is used to define anonymous functions. They are, however, limited to a single line of expression. They, like regular functions, can accept several parameters.

Syntax

lambda arguments: expression

sorted() function

The sorted() function returns a sorted list of the iterable object given.

You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.

Syntax

sorted(iterable, key=key, reverse=reverse)

Parameters

  • iterable − It is a sequence like a tuple, list, string, etc.

  • key − A function that will be executed to determine the order. The default value is None.

  • reverse − A Boolean expression. True sorts ascending, False sorts descending. The default value is False.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a function sortBySurnames() that sorts the list by the last name by accepting the input list of strings as an argument.

  • Create an empty list to store the list of names.

  • Use the for loop to traverse through the input list.

  • Use the split() function(splits a string into a list. We can define the separator; the default separator is any whitespace) to split the current word into a list of words.

  • Append to the above empty list using the append() function(adds the element to the list at the end).

  • Modify the input list empty again to store the result.

  • Traverse in the sorted of the new list by sorting with key as second word(last name).

  • Use the join() function to convert into a string and append it to the input list using the append() function.

  • Return the resultant sorted list by last names.

  • Create a variable to store the input list of strings and print the given list.

  • Call the above-defined sortBySurnames() function by passing the input list as an argument.

Example

The following program returns a sorted list by the last name of an input list using lambda function and sorted() methods –

# creating a function that sorts the list by the last name

# by accepting the input list of strings as an argument
def sortBySurnames(inputList):
   
   # storing the list of names
   newList = []
   
   # traversing through an input list
   for i in inputList:
      
      # splitting the current word into the list of words and
      
      # appending into an above created empty list
      newList.append(i.split())
   
   # making the input list empty again
   inputList = []
   
   # Traversing in the sorted of the new list by sorting with key as second word(lastname)
   for i in sorted(newList, key=lambda k: k[-1]):
      
      # converting to a string using join() and appending it to input list
      inputList.append(' '.join(i))
   
   # returning the sorted list by last names
   return inputList

# input list of names
inputList = ['sachin tendulkar', 'suresh raina', 'hardik pandya']

# printing input list
print('Input List:', inputList)

# calling the sortBySurnames() function by passing the input list as argument
print('Input List after sorting by last names:\n', sortBySurnames(inputList))

Output

On executing, the above program will generate the following output –

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']
Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

Method 2: Using lambda and sort() functions

sort() method

The sort() method sorts the original list in place. It signifies that the sort() method changes the order of the list's elements.

By default, the sort() method uses the less-than operator (<) to sort the entries of a list i.e, in ascending order. In other words, it prioritizes lesser elements above higher ones.

To sort elements from highest to lowest(descending order), use the reverse=True parameter in the sort() method.

list.sort(reverse=True)

Example

The following program returns a sorted list by the last name of an input list using the lambda function and sort() methods –

# creating a function that sorts the input list by surnames

# by accepting the list as an argument
def sortBySurnames(inputList):
   
   # Splitting the input list and sorting with the key as the second word
   inputList.sort(key=lambda k: k.split()[-1])
   
   # returning the sorted list by last names
   return inputList

# input list of names
inputList = ['sachin tendulkar', 'suresh raina', 'hardik pandya']

# printing input list
print('Input List:', inputList)

# calling the sortBySurnames() function bypassing the input list as an argument
print('Input List after sorting by last names:\n', sortBySurnames(inputList))

Output

On executing, the above program will generate the following output –

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']
Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

Conclusion

This article taught us 2 distinct methods for sorting a list of names by last name. We learned how to use the key parameter in the sorted() and sort() functions to sort depending on the nth word or character. Additionally, we learned how to use the join() function to join the list and convert it into a string.

Updated on: 27-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements