×

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

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Falcon Python

Introduction of Python Python is the fastest and the smartest programming language and it is an object oriented language. Python has libraries that can be importedeasily and perform many operations; to...

3 minutes read.

Python Win32 Process

The Win32 process is essentially a Python procedure. This program provides access to advanced Win32 process creation and management features. Process objects are created through the Create method (the constructor)....

6 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

To Do GUI Application 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...

3 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

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...

4 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Weight Conversion GUI 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...

3 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.