Open In App
Related Articles

sort() in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The sort function can be used to sort the list in both ascending and descending order. It can be used to sort lists of integers, floating point numbers, strings, and others in Python. Its time complexity is O(NlogN).

Python sort() Syntax

The syntax of the sort() function in Python is as follows.

Syntax: list_name.sort(key=…, reverse=…)

Parameters:

By default, Python sort() doesn’t require any extra parameters and sorts the list in ascending order. However, it has two optional parameters:

  • key:  function that serves as a key for the sort comparison
  • reverse: If true, the list is sorted in descending order.

Return value: The sort() does not return anything but alters the original list according to the passed parameter.

What is Python sort() Function?

In Python, the sort() function is a method that belongs to the list . It is used to sort in python or the elements of a list in ascending order by default. The sort() method modifies the original list in-place, meaning it rearranges the elements directly within the existing list object, rather than creating a new sorted list.

Sort() in Python Examples

A basic example of Python sort() method.

Example : In this example the below code defines a list named unsorted_list with numeric elements. The sort() method is then applied to the list, which rearranges its elements in ascending order. The sorted list is then printed, showing the result of the sorting operation.

Python3

unsorted_list = [2,4,5,32,6,255,5,42]
unsorted_list.sort()
print("Now it is sorted:", unsorted_list)

                    

Output:

Now it is sorted: [2, 4, 5, 5, 6, 32, 42, 255]

Different Ways to Sort() in Python

In Python, sort() is a built-in method used to sort elements in a list in ascending order. It modifies the original list in place, meaning it reorders the elements directly within the list without creating a new list. The sort() method does not return any value; it simply sorts the list and updates it.

  1. Sorting List in Ascending Order
  2. Sorting List in Descending Order
  3. Sort with custom function Using Key
  4. Sorting List of Strings by Length
  5. Sorting List of Tuples by a Specific Element
  6. Sorting List of Dictionaries by a Specific Key

Sort() in Python using Sorting List in Ascending Order

The `sort()` method in Python is used to sort a list of elements in ascending order. It modifies the original list in-place, rearranging its elements to be in increasing numerical or lexicographical order. The method is applicable to lists containing numerical values, strings, or a combination of both. By default, the sort() in Python sorts a list in ascending order if we do not provide it with any parameters.

Example : In this example the below code demonstrates sorting operations on different types of lists. First, it sorts a list of integers (`numbers`) in ascending order using the `sort()` method. Next, it sorts a list of floating-point numbers (`decimalnumber`) in ascending order.

Python3

# List of Integers
numbers = [1, 3, 4, 2]
 
# Sorting list of Integers
numbers.sort()
 
print(numbers)
 
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
 
# Sorting list of Floating point numbers
decimalnumber.sort()
 
print(decimalnumber)
 
# List of strings
words = ["Geeks", "For", "Geeks"]
 
# Sorting list of strings
words.sort()
 
print(words)

                    

Output:

[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']

Sort() in Python using Sorting List in Descending Order

To sort a list in descending order, set the reverse parameter to True of the sort() function in Python.

my_list.sort(reverse=True)

Example : In this example code defines three lists of different types (integers, floating-point numbers, and strings), sorts them in descending order using the `sort` method with the `reverse=True` parameter, and then prints the sorted lists.

Python3

# List of Integers
numbers = [1, 3, 4, 2]
 
# Sorting list of Integers
numbers.sort(reverse=True)
 
print(numbers)
 
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
 
# Sorting list of Floating point numbers
decimalnumber.sort(reverse=True)
 
print(decimalnumber)
 
# List of strings
words = ["Geeks", "For", "Geeks"]
 
# Sorting list of strings
words.sort(reverse=True)
 
print(words)

                    

Output:

[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']

Sort with Custom Function Using Key

In this method describes a sorting operation with a custom function using the “key” parameter. This allows sorting based on a specific criterion defined by the custom function rather than the default ordering. The custom function is applied to each element, and the list is sorted accordingly.

Example : In this example code defines a function `sortSecond` that returns the second element of a tuple. It then creates a list of tuples, `list1`, and sorts it in ascending order based on the second element using the `sortSecond` function.

Python3

def sortSecond(val):
    return val[1]
 
# list1 to demonstrate the use of sorting
# using second key
list1 = [(1,2),(3,3),(1,1)]
 
# sorts the array in ascending according to
# second element
list1.sort(key=sortSecond)
print(list1)
 
# sorts the array in descending according to
# second element
list1.sort(key=sortSecond,reverse=True)
print(list1)

                    

Output:

[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]

Sorting List of Strings by Length in Sort() in Python

In this method we sorts a list of strings in ascending order of their lengths using the `sort()` function with the `key=len`. This means that the strings are arranged from the shortest to the longest length in the resulting sorted list.

Example : In this example the below code defines a list of strings, words, and then sorts it based on the length of each string using the len() function as the sorting key. Finally, it prints the sorted list.

Python3

# Original list of strings
words = ["apple", "banana", "kiwi", "orange", "grape"]
 
# Sorting by length using the len() function as the key
words.sort(key=len)
 
# Displaying the sorted list
print("Sorted by Length:", words)

                    

Output :

Sorted by Length: ['kiwi', 'apple', 'grape', 'banana', 'orange']

Sorting List of Tuples by a Specific Element

To sort a list of tuples by a specific element, use the `sort()` function with the `key` parameter. Specify a lambda function as the key, targeting the desired element’s index. The tuples will be sorted based on the values of that specific element.

Example : In this method code defines a list of tuples named ‘people,’ where each tuple represents a person’s name and age. It then sorts the list based on the second element of each tuple (age) using the sort method and a lambda function as the sorting key.

Python3

# Original list of tuples
people = [("Alice", 25), ("Bob", 30), ("Charlie", 22), ("David", 28)]
 
# Sorting by the second element of each tuple (age)
people.sort(key=lambda x: x[1])
 
# Displaying the sorted list
print("Sorted by Age:", people)

                    

Output :

Sorted by Age: [('Charlie', 22), ('Alice', 25), ('David', 28), ('Bob', 30)]

Sorting List of Dictionaries by a Specific Key

This method involves using the `sort()` function on a list of dictionaries in Python. By specifying a lambda function as the key parameter, you can sort the list based on a specific key within each dictionary. This enables the list of dictionaries to be arranged in ascending order according to the values associated with the chosen key.

Example : In this example code defines a list of dictionaries called students, where each dictionary represents a student with “name” and “age” keys. It then sorts the list of dictionaries based on the “age” key in each dictionary using the sort method and a lambda function as the key.

Python3

# Original list of dictionaries
students = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 22},
    {"name": "David", "age": 28},
]
 
# Sorting by the 'age' key in each dictionary
students.sort(key=lambda x: x["age"])
 
# Displaying the sorted list
print("Sorted by Age:", students)

                    

Output :

Sorted by Age: [
{'name': 'Charlie', 'age': 22},
{'name': 'Alice', 'age': 25},
{'name': 'David', 'age': 28},
{'name': 'Bob', 'age': 30}
]

Difference between sorted() and sort() function in Python

Let us see the difference between the sorted() and sort() function in Python:

Python sorted()

Python sort()

The sorted() function returns a sorted list of the specific iterable object.The sort() method sorts the list.
We can specify ascending or descending order while using the sorted() functionIt sorts the list in ascending order by default.
Syntax: sorted(iterable, key=key, reverse=reverse)Syntax: list.sort(reverse=True|False, key=myFunc)
Its return type is a sorted list.We can also use it for sorting a list in descending order.

Can be used with any iterable, even if comparison between elements is not defined

Requires elements to be comparable using the < and > operators

Maintains the relative order of equal elements, making it stable.

May not be stable; the order of equal elements may change.

O(n log n) time complexity for most cases.

O(n log n) time complexity for most cases.

It can only sort a list that contains only one type of value.It sorts the list in place.

Supports a key parameter for custom sorting criteria.

Also supports a key parameter for custom sorting criteria.

Requires additional memory for the new sorted list.

Performs the sorting in-place, saving memory.

To know more please refer Python difference between the sorted() and sort() function.



Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads