Methods and Functions

Python List sort ()

Lists are a data structure in Python used to store multiple items in a single variable. The items in a list are arranged in an order. The items stored can be changed after defining the list and they can be duplicated within the list as well.  The items that are stored in the list are assigned an index. An index is a whole number that identifies one item of the list from another. The indexing in the list begins from 0 and extends up to the number of items that are stored in the list. Thus, the first item of the list has an index [0], the second item [1], and so on. Let us learn sort list python in detail. 

Sort list Python

Source 

 

When lists are defined, they are stored in a specific order. This order cannot be changed once the list has been created. New items that are added to the list will be placed at the end of the list and assigned the specific index. 

Syntax of defining a list in Python: name of the list = [items of the list separated by a comma]

In Python, a list can be arranged in order with the help of the sort () method. The method sort list Python can be used to arrange the list in different orders based on the parameters that are passed in it. 

Syntax of using the sort () method: list_name.sort ()

Another method sorted () is also available in Python that can be used to order the items of the list. When you apply the sort () method, it will change the list without returning any value, whereas the sorted () method returns the sorted list without changing the list.  

Syntax for sorted () method: sorted (name of the list, key = …, reverse = …)

Sorting is an essential function to be used in data structures. Through the method of sort list Python, you can arrange a large amount of data in the way you want. You can also access specific data based on their position in a sorted list. For example, if you have data of students in a class that includes their name, roll number, birth year, and age, then you can arrange the data structure according to their age. You can also arrange the names of the students alphabetically for roll call.  

Sort () Parameters 

When no parameters are passed in the sort (), then it will by default arrange the items in the list alphanumerically and in ascending order. 

However, to sort the list in a definite order, the parameters that are required in sort () are reverse and key. If the reverse is true, then the order of the list is reversed. The key parameter works as a comparison key. 

Syntax of sort () method with parameters: list_name.sort (key = …, reverse = …)

Return Value from sort ()

There is no return value obtained from sort list Python. It changes the order of the list without returning any value. To get a return value, one can use the sorted () method. 

Example 1: Sort a given list. 

                    

# sort list alphabetically 

my_list = [“banana”, “mango”, “orange”, “pineapple”, “apple”]

my_list.sort ()

print (my_list)

Output:

                    

[‘apple’, ‘banana’, ‘mango’, ‘orange’, ‘pineapple’]

                    

#sort list numerically 

list_1 = [67, 38, 90, 55, 282, 646, 71]

list_1.sort ()

print (list_1)

Output:

                    

[38, 55, 67, 71, 90, 282, 646]

Sort in Descending Order 

To arrange the items of a list in descending order, you will have to reverse the order of the items stored in a sorted list. To reverse the order, the reverse parameter is used. The argument that will be added with the sort () method will be reverse = True. 

If you want to use the sorted () method, you can add the argument reverse = True in the parameters to get the list sorted in descending order. The syntax is shown below.

sorted (name of the list, reverse = True)

Example 2: Sort the list in descending order. 

                    

# sort list alphabetically 

my_list = [“banana”, “mango”, “orange”, “pineapple”, “apple”]

my_list.sort ()

print (my_list)

Output:

                    

[‘pineapple’, ‘orange’, ‘mango’, ‘banana, ‘apple’]

                    

#sort list numerically 

list_1 = [67, 38, 90, 55, 282, 646, 71]

list_1.sort ()

print (list_1)

Output:

                    

[646, 282, 90, 71, 67, 55, 38]

Sort with Custom Function Using key 

You can also sort list Python based on your choice. You can sort the items based on the character length, or any other function desirable. The function based on which you want to sort the list will be mentioned with the key parameter. Thus, the syntax of the sort () method to be used in the case will be as shown below. 

list_name.sort (key = len)

The code will sort the elements present in the list based on the length of their characters in ascending order. Thus, the element with the lowest length will be stored first and the one with the longest string length will be placed last. 

You can, alternatively, also use the sorted () method to get a return value. To custom sort the list using the sorted () method, the following syntax will be followed. 

sorted (name of the list, key = len)

Remember that when using a function through a key parameter, the list will by default arranged in ascending order, that is, the lowest number will be placed first.

You can even create a function according to which you want the list to be sorted. The example below shows how you can define a function and use its parameters to order the elements of the list. 

Example 3: Sort the list using key.   

                    

def func_1 (n):

              return abs (n - 10)

my_list = [60, 76, 59, 90, 100, 2, 8]

my_list.sort (key = func_1)

print (my_list)

Output:

                    

[8, 2, 59, 60, 76, 90, 100]

Sort list Python

Source 

Here is another example. This example includes a list that contains dictionaries. The data structure contains information about students in a class. 

                    

students = [ 

{‘Name’: ‘Akash’, ‘age’: 16, ‘roll number’: 798},

{‘Name’: ‘Nikhil’, ‘age’: 15, ‘roll number’: 890},

{‘Name’: ‘Priya’, ‘age’: 17, ‘roll number’: 621},

{‘Name’: ‘Rita’, ‘age’: 14, ‘roll number’: 500}]

students.sort (key = lambda x: x.get(‘Name’))

print (students)

students.sort (key = lambda x: x.get(‘age’))

print (students)

students.sort (key = lambda x: x.get(‘roll number’))

print (students)

Output:

                    

{‘Name’: ‘Akash’, ‘age’: 16, ‘roll number’: 798}, {‘Name’: ‘Nikhil’, ‘age’: 15, ‘roll number’: 890}, {‘Name’: ‘Priya’, ‘age’: 17, ‘roll number’: 621}, {‘Name’: ‘Rita’, ‘age’: 14, ‘roll number’: 500}]

{‘Name’: ‘Rita’, ‘age’: 14, ‘roll number’: 500}, {‘Name’: ‘Nikhil’, ‘age’: 15, ‘roll number’: 890}, {‘Name’: ‘Akash’, ‘age’: 16, ‘roll number’: 798}, {‘Name’: ‘Priya’, ‘age’: 17, ‘roll number’: 621}]

{‘Name’: ‘Rita’, ‘age’: 14, ‘roll number’: 500}, {‘Name’: ‘Priya’, ‘age’: 17, ‘roll number’: 621}, {‘Name’: ‘Akash’, ‘age’: 16, ‘roll number’: 798}, {‘Name’: ‘Nikhil’, ‘age’: 15, ‘roll number’: 890}]

 

Q & A on Sort List Python

1. How do you sort a list in Python?

Answer: We can sort the list in Python using the sort () or sorted () method. You can also use a loop. 

2. How do I sort a list in Python 3?

Answer: To sort a list in Python 3, the easiest way is to use the sort () and sorted () methods. 

3. What does sort () do in Python?

Answer: sort () method rearranges the elements of a list in ascending or any other order specified.   

4. How do you sort a list in descending order in Python? 

Answer: To sort a list in descending order, one will have to define the parameter reverse = True in the sort () method.  

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.