Python list.sort key

Python List sort[] - Sorts Ascending or Descending List

The list.sort[] method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items.

Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.

Syntax:

list.sort[key=None, reverse=False]

Parameters:

  1. key: [Optional] A function that extracts a comparison key from each list element while sorting.
  2. reverse: [Optional] If true, the sorted list will be reversed. By default, it is False.

Return Value:

No return value. It sorts the list itself.

The following example demonstrates the sort[] function on numeric lists.

Example: Sort Numeric List
Copy
nums = [1, 5, 3, 4, 2, 10, 6, 8, 7, 9] nums.sort[] print['List in Ascending Order: ', nums] nums.sort[reverse=True] print['List in Descending Order: ', nums]
Output
List in Ascending Order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] List in Descending Order: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The sort[] method can also be used on character lists.

Example: Sort Char List
Copy
al = ['a','d','e','c','b'] al.sort[reverse=True] print['List in Descending Order: ', al] al.sort[] print['List in Ascending Order: ', al]
Output
List in Descending Order: ['e', 'd', 'c', 'b', 'a'] List in Ascending Order: ['a', 'b', 'c', 'd', 'e']

The following example sorts the string list in alphabetical order.

Example: Sort String List
Copy
cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.sort[] print['List in Ascending Order: ', cities] cities.sort[reverse=True] print['List in Descending Order: ', cities]
Output
List in Ascending Order: ['London', 'Mumbai', 'New York', 'Paris'] List in Descending Order: ['Paris', 'New York', 'Mumbai', 'London']

Using key Parameter

Use the key parameter to set the built-in or custom function to compare each element of a list and sort it. For example, the following uses the built-in len[] function that returns the length of each element and sorts based on the length of each element.

Example: Sort by String Length
Copy
cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.sort[key=len] print['List in Ascending Order of the length: ', cities] cities.sort[key=len, reverse=True] print['List in Descending Order of the length: ', cities]
Output
List in Ascending Order of the length: ['Paris', 'Mumbai', 'London', 'New York'] List in Descending Order of the length: ['New York', 'Mumbai', 'London', 'Paris']

Sort List of Class Objects

The following example shows how to sort a list whose elements are the objects of the custom class.

Example: Sort List of Objects
Copy
class student: name='' age=0 def __init__[self, name, age]: self.name = name self.age = age s1 = student['Bill', 25] s2 = student['Steve', 29] s3 = student['Ravi', 26] student_list = [s1, s2, s3] # student_list.sort[] # raise an error student_list.sort[key=lambda s: s.name] # sorts using lambda function print['Students in Ascending Order:', end=' '] for std in student_list: print[std.name, end=', '] student_list.sort[key=lambda s: s.name, reverse=True] # sorts using lambda function print['Students in Descending Order:', end=' '] for std in student_list: print[std.name, end=', ']
Output
Students in Ascending Order: Bill, Ravi, Steve, Students in Descending Order: Steve, Ravi, Bill,

In the above example, the lambda function lambda s: s.name set to the key argument. So, it will return the name of each student object for comparison. Direct use of student_list.sort[] will raise an error because the < operator cannot compare objects. You can define a function instead of using the lambda function as a key argument.

Video liên quan

Chủ Đề