Python Sort Lists – Everything You Need to Know

Updated on July 19, 2024

Article Outline

Sorting is a fundamental operation in any computer programming language. It allows you to organise data in a desired order for easier manipulation and analysis. In this article, we will learn how to sort the list in Python using the sort() method, which is an inbuilt method in the Python programming language.

sort() method in Python

In the Python programming language, we have asort() method. This is an inbuilt method that sorts the original list directly.

 

Syntax of sort() method

 

list_name.sort(reverse=””,key=...)

 

This method accepts two parameters that are described below:

  • reverse(Optional): This is an optional parameter. If this parameter is true, it will sort the
    list in reverse order. By default, this parameter has a false value.
  • key(Optional): This parameter is also optional. This parameter specifies the sorting criteria.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Sort list items in ascending order

By default, the sort() method sorts the list in ascending order. Ascending order means arranging the
items from lowest to highest value. The lowest value will be the left-hand side, and the highest value will be the
right-hand side.

 

The following program demonstrates sorting the list of numbers in ascending order.

 

Source Code

 

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] numbers.sort() print(numbers)

 

Output

 

[1, 1, 2, 3, 4, 5, 5, 6, 9]

 

Also read: Python Data Types

Sort list items in descending order

Descending sorting is the opposite of ascending order. In descending order, we sort the elements and arrange them from highest to lowest value. To sort the list in descending order, you have to enable the reverse parameter in the sort() method. Its value must be true when working with descending sorting.

 

The following program demonstrates sorting the list of items in descending order.

 

Source Code

 

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] numbers.sort(reverse=True) print(numbers)

 

Output

 

[9, 6, 5, 5, 4, 3, 2, 1, 1]

Sort list items using the key parameter

We can also perform customised sorting operations by using the key parameter. The key parameter accepts a function that specifies which type of sorting you are performing. In this example, we will pass the inbuilt len() function into the key parameter for sorting the list of elements.

 

The following program demonstrates the sort() method with the key parameter:

 

Source Code:

 

heroes = ["Harry Potter", "Ron", "Voldemort", "Doraemon", "Shinchan", "Ben 10"] heroes.sort(key=len) print(heroes)

 

Output

 

['Ron', 'Ben 10', 'Doraemon', 'Shinchan', 'Voldemort', 'Harry Potter']

Sort a list of strings

We can also sort the list of strings using the sort() method. The following program demonstrates the list of string examples.

 

Program

 

cities = ["Harry", "Ron", "Hermoine"] # sort in dictionary order cities.sort() print(f"Dictionary order: {cities}") # sort in reverse dictionary order cities.sort(reverse = True) print(f"Reverse dictionary order: {cities}")

 

Output

Dictionary order: ['Harry', 'Hermoine', 'Ron'] Reverse dictionary order: ['Ron', 'Hermoine', 'Harry']

The difference between sort() and sorted() method

The Python programming language has one more method, sorted(). In this section, we will try to differentiate the sort() and sorted() methods.

 

sort() Method  sorted() Method
This method sorts elements in the original list This method returns a new sorted list in Python
This method syntax is  “list.sort(key=None,reverse=False)” This method syntax is “sorted(iterable,key=None reverse=False)”
This method returns nothing This method returns a sorted list
Yes, using the key and reverse parameters. Yes, using the key and reverse parameters.
This method usage is list.sort() This method usage is sorted(iterable_list)

Conclusion

Every developer must know how to sort a list in Python. This is a fundamental skill every developer should master this skill. In this article, we learned about various kinds of approaches for sorting the list in Python. There are two inbuilt methods in Python for sorting a list: the ‘sort()’ and ‘sorted()’ methods. Both methods sort the array. The first method does not return any sorted list. However, the second method returns the sorted list. If you want to learn more about the Python language, enrol in the Accelerator Program in Business Analytics and Data Science.

 

FAQs
In the Python language, the most efficient algorithm is timesort(). It is the default sorting algorithm for lists in the Python programming language. It is a hybrid algorithm derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.
Python offers several built-in sorting algorithms, including Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, Merge Sort, Tim Sort, and Heap Sort.
The easiest way to sort a list in Python is by using the built-in ‘sorted()’ functions or the ‘sort()’ method of lists.
The sort() method is a built-in method in Python. This method sorts the list in ascending order by default. However, you can modify the order from ascending order to descending order by specifying a reverse parameter in this method.
Python has an inbuilt sort method for sorting the list. There are two methods in Python for sorting a list: sort() and sorted().

Updated on July 19, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved