×

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax and the mechanism of the sort method will be discussed, along with example programs.

Use of sort() function

This built-in method is used to sort the elements of the given list in order, either ascending or descending order.

Instead on writing a whole logic to sort the elements, we can simply use this method to get the mechanism with a smaller number of lines.

Syntax

list_name. sort (key = ____, reverse = _____)

Parameters in the syntax:

  • Key: Represents the function that serves as a key for the comparison to sort the elements in the list.
  • Reverse: If mentioned true, the sorted list will be reversed or it will be sorted in the descending order.

The sort () method does not return any value. It just modifies the original list, and if we want it we can print the original list.

sort () vs. sorted ()

There is another function in Python, which is sorted (), and is also used to sort the elements of a list in order but the difference between using these two functions would be:

  • The sort () function as mentioned above does not return any value rather changes/ modifies the original list into the sorted list
  • The sorted () function returns the sorted list and does not change a thing in the original list. This can be used when we need the sort made in a function.

Example

Let us look into it with a simple example to sort the vowels in the alphabetical order:

Vowels = [‘u’, ‘e’, ‘a’, ‘i’, ‘o’]

Vowels. sort ()

This modifies the vowels list but doesn’t return or print anything. If we need the output, we need to print it:

print (Vowels)

Now, the output will be [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

To sort in descending order:

As discussed in the syntax, the function has an optional parameter reverse which when declared True, sorts the list in the descending order.

Example:

Vowels = [‘u’, ‘e’, ‘a’, ‘i’, ‘o’]

Vowels. sort (reverse = True)

print (Vowels)

Output:

[‘u’, ‘o’, ‘i’, ‘e’, ‘a’]

As you can see, the alphabets are sorted in the reverse order of the alphabetical order which is the descending order.

Utilizing key function

If we need to sort a list in ascending or descending order, then we can use the simple syntax but if we need some custom sorting order to follow, we can use the key parameter specified in the syntax.

Assigning the key to a sorting function enables the custom sort we want.

Example program 1:

Students = [

    {'Name': 'Louis', 'age': 15, 'marks': 98},

    {'Name': 'Zayn', 'age': 16, 'marks': 97},

    {'Name': 'Liam', 'age': 17, 'marks': 92},

    {'Name': 'Harry', 'age': 16, 'marks': 89},

]

def get_name (Students):

    return Students. get ('Name')




def get_age (Students):

    return Students. get ('age')




def get_marks (Students):

    return Students. get ('marks')



Students. sort (key = get_name)

print (Students, end = '\n\n')



Students. sort (key = get_age)

print (Students, end = '\n\n')



Students. sort (key = get_marks, reverse = True)

print (Students, end = '\n\n')

Output:

[{'Name': 'Harry', 'age': 16, 'marks': 89}, {'Name': 'Liam', 'age': 17, 'marks': 92}, {'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Zayn', 'age': 16, 'marks': 97}]



[{'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Harry', 'age': 16, 'marks': 89}, {'Name': 'Zayn', 'age': 16, 'marks': 97}, {'Name': 'Liam', 'age': 17, 'marks': 92}]



[{'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Zayn', 'age': 16, 'marks': 97}, {'Name': 'Liam', 'age': 17, 'marks': 92}, {'Name': 'Harry', 'age': 16, 'marks': 89}]

Explanation:

As you can see, we declared a dictionary of Students and their details name, age, and marks. Then, we used the sort () function to sort the dictionary using different parts.

In the first sort, we sorted the dictionary by means of the names of the students, in the second, age and in the third, we used marks to sort the students. You can observe the difference in the sorting order in the output of the program.

In order to get the key functions, we created our own custom functions get_name, get_age and get_marks that return the values we want to sort the keys of the dictionary. Python by default sorts the strings in alphabetical order and integers in the ascending order. To change the order to descending order, we used the reverse parameter and assigned it to True.

Example program 1:

In Python, if we sort tuples, by default the sorting will be done with respect to the first elements of the tuples. We can change it to the second element and sort the tuples, here is the example using the sort () method:

def take_second (elem):

    return elem [1]

tuple_list = [(2, 2), (3, 4), (4, 1), (1, 3)]

tuple_list.sort (key=take_second)

print ("Sorted list:", tuple_list)

Output:

Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Explanation:

We used a function to select the second elements in the tuples in the tuple_list and then we assigned the key of the sort () method to the function. This way, we ordered the tuples according to the ascending order of the second elements of the tuples in the list.

In the same example, if we did not specify the key to the second elements:

tuple_list = [(2, 2), (3, 4), (4, 1), (1, 3)]

tuple_list.sort()

print("Sorted list:", tuple_list)

Output:

Sorted list: [(1, 3), (2, 2), (3, 4), (4, 1)]

Explanation:

Now, we didn’t specify any custom key function. By default, the tuples are arranged in the order of the ascending order of the first elements of the tuples in the list.

Note: Find out the difference between both the outputs and then you can differentiate the difference.

Example:

num = [1, 3, 4, 2]

num.sort()

print(num)

dec_num = [2.01, 2.00, 3.67, 3.28, 1.68]

dec_num.sort()

print(dec_num)

strings = ["Tutorials", "and", "Examples"]

strings.sort()

print(strings)

Output:

[1, 2, 3, 4]

[1.68, 2.0, 2.01, 3.28, 3.67]

['Examples', 'Tutorials', 'and']

Explanation:

In this example, we sorted an integer list, a floating-point number list, and a string list. As we discussed above, the integers and floating point numbers are sorted in ascending order of the values and the strings are sorted in the alphabetical or ASCII order.


Related Topics

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python Banner

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.