The Wayback Machine - https://web.archive.org/web/20240828180946/https://www.geeksforgeeks.org/sort-in-python/
Open In App

sort() in Python

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
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.

Python
# 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.

Python
# 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.

Python
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.

Python
# 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.

Python
# 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.

Python
# 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.

sort() in Python – FAQs

What is the sort() method in Python?

The sort() method is a built-in list method in Python that sorts the elements of a list in place. It means that the original list is modified to be in sorted order, and it does not return a new list.

Syntax:

list.sort(key=None, reverse=False)
  • key: A function that serves as a key for the sort comparison. Defaults to None.
  • reverse: A boolean value. If True, the list elements are sorted as if each comparison were reversed.

How to Sort a List Alphabetically in Python?

To sort a list alphabetically, you can use the sort() method or the sorted() function.

Using sort() method:

words = ["banana", "apple", "cherry"]
words.sort()
print(words) # Output: ['apple', 'banana', 'cherry']

Using sorted() function:

words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words) # Output: ['apple', 'banana', 'cherry']

How to Use the sorted() Function in Python?

The sorted() function returns a new sorted list from the elements of any iterable.

Syntax:

sorted(iterable, key=None, reverse=False)
  • iterable: Any iterable (list, tuple, dictionary, etc.).
  • key: A function that serves as a key for the sort comparison. Defaults to None.
  • reverse: A boolean value. If True, the sorted list is reversed.

Example:

numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 3, 4, 5, 9]

What are Key Functions in Python sort()?

Key functions in the sort() method (or sorted() function) allow you to customize the sorting order by specifying a function of one argument that is used to extract a comparison key from each list element.

Example:

# Sort by length of the string
words = ["banana", "apple", "cherry"]
words.sort(key=len)
print(words) # Output: ['apple', 'banana', 'cherry']

How to Sort a Python Dictionary by Value?

To sort a dictionary by its values, you can use the sorted() function in combination with the items() method and a key function.

Example:

# Sorting dictionary by value
dict_data = {'banana': 3, 'apple': 4, 'cherry': 2}
sorted_dict = dict(sorted(dict_data.items(), key=lambda item: item[1]))
print(sorted_dict) # Output: {'cherry': 2, 'banana': 3, 'apple': 4}


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
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
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
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
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Sort a tuple by its float element
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'),
3 min read
Python | Sort a list according to the second element in sublist
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() meth
9 min read
Python | Sort words of sentence in ascending order
Given a sentence, sort it alphabetically in ascending order. Examples: Input : to learn programming refer geeksforgeeksOutput : geeksforgeeks learn programming refer to Input : geeks for geeksOutput : for geeks geeks Approach 1 : We will use the built-in library function to sort the words of the sentence in ascending order. Prerequisites: split() s
2 min read
Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers, the task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even because of its index 0. Examples: Input: a
2 min read
numpy.sort() in Python
numpy.sort() : This function returns a sorted copy of an array. Parameters : arr : Array to be sorted. axis : Axis along which we need array to be started. order : This argument specifies which fields to compare first. kind : [‘quicksort’{default}, ‘mergesort’, ‘heapsort’]Sorting algorithm. Return : Sorted Array # importing libraries import numpy a
1 min read
Python | Sort an array according to absolute difference
Given an array of N distinct elements and a number val, rearrange the array elements according to the absolute difference with val, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences. Examples: Input: val = 6, a = [7, 12, 2, 4, 8,
3 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
How to visualize selection and insertion sort using Tkinter in Python?
In this article, we are going to create a GUI application that will make us visualize and understand two of the most popular sorting algorithms better, using Tkinter module. Those two sorting algorithms are selection sort and insertion sort. Selection sort and Insertion sort are the two most popular algorithms. Selection sort is a comparison-based
6 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Sort the list alphabetically in a dictionary
In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is a typical activity that takes on added interest wh
3 min read
Python | Numpy matrix.sort()
With the help of matrix.sort() method, we are able to sort the values in a matrix by using the same method. Syntax : matrix.sort() Return : Return a sorted matrix Example #1 : In this example we are able to sort the elements in the matrix by using matrix.sort() method. # import the important module in python import numpy as np # make matrix with nu
1 min read
Python | Ways to sort list of strings in case-insensitive manner
Given a list of strings, A task is to sort the strings in a case-insensitive manner. Given below are a few methods to solve the task. Method #1: Using casefold() C/C++ Code # Python code to demonstrate to sort list of # strings in case insensitive manner # Initialising list ini_list = ['akshat', 'garg', 'GeeksForGeeks', 'Alind', 'SIngh', 'manjeet',
4 min read
Python | sort list of tuple based on sum
Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using the technique of Bubble Sort to we can perform the s
4 min read
Python MongoDB - Sort
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of
2 min read
Insertion Sort Visualization using Matplotlib in Python
Prerequisites: Insertion Sort, Using Matplotlib for Animations Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, Approach: We will generate an array
3 min read
Sort a Pandas Series in Python
Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. Now, Let's see a program to sort a Pandas Series. For sorting a pandas series the Series.sort_values() method is used. Syntax: Series.sort_values(axis=0, ascending=True, inplace=Fa
3 min read
3D Visualisation of Insertion Sort using Matplotlib in Python
Prerequisites: Insertion Sort, Introduction to Matplotlib Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use matplotlib to plot bar graphs and animate them to represent the
3 min read
3D Visualisation of Quick Sort using Matplotlib in Python
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use Matplotlib to plot bar graphs and animate them to represent the elements of the array. Let's see the 3D Visualizations of
3 min read
Visualizing Bubble sort using Python
Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. We tend to understand those things more which are
3 min read
Sort Boxplot by Mean with Seaborn in Python
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.Box Plot is the visual representation of the depicting
3 min read
How to Sort by Column in a file using Python?
For sorting files particularly CSV or tab or space separated files, We use Pandas and sort the data. Because Pandas provide multiple functions to achieve the same. But one thing we have to realize here is Pandas are built for bigger data sets and not for smaller files. For small files, we can even use the built-in functions provided by python, and
5 min read
Practice Tags :