Open In App

sort() in Python

Last Updated : 18 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
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() function It 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.



Similar Reads

Sort a list in Python without sort Function
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method. Sort a List Without Using Sort Functio
3 min read
Sort a Dictionary Without Using Sort Function in Python
As we all know Dictionaries in Python are unordered by default, which means they can’t be sorted directly. However, we can sort the keys or values of a dictionary and create a new sorted dictionary from the sorted keys or values. We can sort a list in a Dictionary using the inbuilt dictionary sort() function. But in this article, we will learn how
3 min read
Add elements in start to sort the array | Variation of Stalin Sort
Stalin sort (also 'dictator sort' and 'trump sort') is a nonsensical 'sorting' algorithm in which each element that is not in the correct order is simply eliminated from the list. This sorting algorithm is a less destructive variation of Stalin sort, that will actually sort the list: In this case, the elements that are not in order are moved to the
6 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
7 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Ways to sort list of dictionaries by values in Python – Using itemgetter
In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article. In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently utilized in a variety of applications, from those i
3 min read
Python | Sort a List according to the Length of the Elements
In this program, we need to accept a list and sort it based on the length of the elements present within. Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "a
4 min read
Sort the words in lexicographical order in Python
Given a strings, we need to sort the words in lexicographical order (dictionary order). Examples : Input : "hello python program how are you" Output : are hello how program python you Input : "Coders loves the algorithms" Output : Coders algorithms loves the Note: The words which have first letter is capital letter they will print according alphabe
2 min read
Practice Tags :
three90RightbarBannerImg