×

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 complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Python Skyline

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

3 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

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

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.