(Translated by https://www.hiragana.jp/)
Python sorted() Function - GeeksforGeeks
Open In App

Python sorted() Function

Last Updated : 01 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python sorted() function returns a sorted list. It is not only defined for the list and it accepts any iterable (list, tuple, string, etc.).

Example

Python3




print(sorted([4, 1, 3, 2]))


Output

[1, 2, 3, 4]

Python sorted() Function Syntax

sorted(iterable, key, reverse)

Parameters:

  • Iterable: sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
  • Key(optional): A function that would serve as a key or a basis of sort comparison.
  • Reverse(optional): If True, then the iterable would be sorted in reverse (descending) order, by default it is set as False.

Return: Returns a list with elements in sorted order.

How to Use sorted() Function in Python?

Using sorted() function is very easy. It is a built in function in Python and can be used with any iterable. Let’s understand it better with a example:

Example:

Python3




# creating a list
counting = [4,1,5,2,3]
#print sorted list
print(sorted(counting))


Output

[1, 2, 3, 4, 5]

More Sorted() Function Examples

Lets look at some of the use cases of sorted() function:

1. Sorting a Python list using sorted() function

In this example, we have applied sorted on the Python list.

Python3




x = [2, 8, 1, 4, 6, 3, 7]
  
print("Sorted List returned :", sorted(x))
  
print("Reverse sort :", sorted(x, reverse=True))
  
print("\nOriginal list not modified :", x)


Output

Sorted List returned : [1, 2, 3, 4, 6, 7, 8]
Reverse sort : [8, 7, 6, 4, 3, 2, 1]

Original list not modified : [2, 8, 1, 4, 6, 3, 7]

2. Sorting different data types with sorted() function

In this example, we have used sorted() on different datatypes like list, tuple, string, dictionary, set, and frozen set.

Python3




# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
  
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
  
# String-sorted based on ASCII translations
x = "python"
print(sorted(x))
  
# Dictionary
x = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
print(sorted(x))
  
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
  
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))


Output

['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['h', 'n', 'o', 'p', 't', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']

3. Reverse sorting using Python sorted()

Sorting a string in lexicographically reverse order by setting reverse=True in the sorted() function.

Python3




# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
    
# initializing string 
test_string = "geekforgeeks"
    
# printing original string 
print("The original string : " + str(test_string))
    
# using join() + sorted() + reverse
# Sorting a string 
res = ''.join(sorted(test_string, reverse = True))
        
# print result
print("String after reverse sorting : " + str(res))


Output

The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

4. Python Sorted() with lambda

Using sorted() inside the Python lambda function.

Python3




import functools
test_string = "geekforgeeks"
  
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
res = functools.reduce(lambda x, y: x + y,
                       sorted(test_string, 
                              reverse=True))
print("String after reverse sorting : " + str(res))


Output

The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

5. Sorted() in Python with len()

In this example, we are sorting the list based on its length. The string of the smallest length should come first.

Python3




L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))


Output

Normal sort : ['aaa', 'b', 'cccc', 'dd']
Sort with len : ['b', 'dd', 'aaa', 'cccc']

The key can also take user-defined functions as its value for the basis of sorting.

Example:

Python3




# Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
    return x % 7
  
L = [15, 3, 11, 7]
  
print("Normal sort :", sorted(L))
print("Sorted with key:", sorted(L, key=func))


Output

Normal sort : [3, 7, 11, 15]
Sorted with key: [7, 15, 3, 11]

6. Sorting a list in ascending order with sorted()

In my_list, we have a list of integer values. We then use the sorted function to sort the list in ascending order. The sorted function takes the iterable to be sorted as its first argument and returns a new list that contains the sorted elements.

In my_string, we have a string. We then use the sorted function to sort the characters in the string in ascending order. The sorted function treats the string as an iterable of characters and returns a new list that contains the sorted characters.

In my_tuples, we have a list of tuples that contains integers and strings. We have used the sorted function to sort the list based on the second element of each tuple. To achieve this we have passed a lambda function as the key argument to the sorted function.

Python3




my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_list = sorted(my_list)
print(sorted_list)  
  
my_string = "hello, world!"
sorted_string = sorted(my_string)
print(sorted_string)  
  
my_tuples = [(1, "one"), (3, "three"), (2, "two"), (4, "four")]
sorted_tuples = sorted(my_tuples, key=lambda x: x[1])
print(sorted_tuples)


Output

[1, 1, 2, 3, 4, 5, 5, 6, 9]
[' ', '!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

7. Sorting a List of Dictionaries by a Specific Key using sorted()

In this example, we are sorting the list of dictionaries with a specific key.

Python3




students = [
    {'name': 'John', 'age': 20},
    {'name': 'Alice', 'age': 18},
    {'name': 'Bob', 'age': 22}
]
sorted_students = sorted(students,key=lambda x: x['age'])
print(sorted_students)


Output

[{'name': 'Alice', 'age': 18}, {'name': 'John', 'age': 20}, {'name': 'Bob', 'age': 22}]

8. Sorting a List of Custom Objects

In this example, we are creating a custom class named Person with two instance variables name and age and we are creating three objects of the Person class and inserting objects into lists. We are using the Sorted Function which sorting the Person’s objects.

Python3




class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
  
  
people = [
    Person('John', 25),
    Person('Alice', 18),
    Person('Bob', 30)
]
sorted_people = sorted(people, key=lambda x: x.age)
print(sorted_people)


Output

[Person(name='Alice', age=18), Person(name='John', age=25), Person(name='Bob', age=30)]

We have covered the definition, syntax and examples of sorted() function in Python. Hope this has answered your question on ” How to use sorted function in Python?”.

sorted() function should not be confused with sort() list method, as they are different.

Hope this article helped you in understanding sorted() function in Python.



Previous Article
Next Article

Similar Reads

heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
Merge two sorted arrays in Python using heapq
Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge two sorted arrays link. We will solve this proble
2 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Check if list is sorted or not
The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved. Method #1 : Naive method
5 min read
Python sorted containers | An Introduction
Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order. Features: Pure-Python Fully documented Bench
6 min read
Python | Returning index of a sorted list
Sort a list in python and then return the index of elements in sorted order. Examples: Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3]. Meth
3 min read
Python | Relative sorted order in Matrix
Sometimes, while working with Python Matrix, we can have data arranged randomly and we can have a requirement in which we need to get the element position in sorted order of Matrix. Let's discuss a certain way in which this task can be performed. Method : Using list comprehension + enumerate() + sort() + lambda The solution to problem can be achiev
4 min read
Python - Get a sorted list of random integers with unique elements
Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end. Examples: Input: num = 10, start = 100, end = 200 Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180] Input: num = 5, start = 1, end = 100 Output: [37, 49, 64, 84, 95] To generate random numbers in Python, randint() functi
2 min read
How to get the indices of the sorted array using NumPy in Python?
We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array. Syntax: numpy.argsort(arr, axis=-1, kind=’quick
2 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir() functionUsing glob() functions Method 1: Using o
3 min read
Get sorted file names from a directory by creation date in Python
In this article, we will understand how to retrieve sorted file names from a directory using Python. For this, we would make use of the Python glob library's glob function. There is no need to install this module externally because it is already included with Python. Firstly, The glob function would be used to obtain the list of files/directories w
3 min read
Python - Difference between sorted() and sort()
Sorting means rearranging a given sequence of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the elements in the respective data structure. For example, The below list of characters is sorted in increasing order of their ASCII values. That is, the character with a lesser ASCII
6 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns. Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this yourself first. Naive Solution: Here's a naive, n
15+ min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 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 Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a U
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Article Tags :
Practice Tags :