Top 3 Methods to Sort list in Python

Currently i am new to Python and i want to sort list in Python. My goal is to explore various ways to do this such as using sort() method, sort function, and other methods.

1. Sort List in Python using sort() Method

The sort() method is a built-in list method in python that modifies the list in place. It sorts the list in ascending order by default, but it can also sort in descending order if specified.

Syntax of List sort()

list.sort(key=None, reverse=False)

key (Optional): A function that defines the sorting criteria.

reverse (Optional): If True, the list will be sorted in descending order. By default, it’s set to False, which sorts the list in ascending order.

Example of Using sort() to Sort list in python:-

my_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort()
print(my_list)  #Output [1, 1, 2, 3, 4, 5, 9]

To sort in descending order, you can pass reverse=True to the Sorting method.

my_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 5, 4, 3, 2, 1, 1]

Read also: How to Structure Django Templates

Using sort() we can modifies the list in place, the sorted() function returns a new sorted list, leaving the original list unmodified. This makes sorted() a more functional approach, you don’t need the original list.

Syntax of sorted()

sorted(iterable, key=Nobe, key=False)

Example of Using sorted() to Sort List in Python

my_list = [3, 1, 4, 1, 5, 9, 2]
sorted_list = sorted(my_list)
print(sorted_list)  #Output [1, 1, 2, 3, 4, 5, 9]

Difference between sort() and sorted()

  • sort() is an instance method specific to lists. It modifies the list in place and return None.
  • sorted() is a more flexible built-in function that works with any iterable and return a new sorted list, leaving the original data unchanged.

3. Sort List in Python using Key Parameter

Python allows you to sort list using custom key function. This is done through the key parameter in both sort() and sorted(). For example, you can sort a list of strings by length:

my_list = ["apple", "banana", "cherry", "date"]
my_list.sort(key=len)
print(my_list)  # Output: ["date", "apple", "banana", "cherry"]

You can Apply Similar Sorting Criteria Using sorted() as well:

my_list = ["apple", "banana", "cherry", "date"]
my_list = sorted(my_list, key=len)
print(my_list)  # Output: ["date", "apple", "banana", "cherry"]

Conclusion: Efficiently Sort List in Python

Knowing how to sort a list in Python is essential when dealing with data. You can either use the sort() method, which changes the list directly, or the sorted() function, which create a new sorted list. Both options let you customize how you sort using the key parameter and easily switch between ascending or descending order with the reverse flag.

I hope this article on Top 3 Methods to Sort List in Python will help you.

For more information read W3Schools Python List Sort()