×

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

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.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

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.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

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.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Io stringio Python

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

7 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

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

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.

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios...

5 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.