Python sorted() Function
Python sorted() function returns a sorted list from the iterable object.
Python sorted() Function Syntax
Syntax: sorted(iterable, key, reverse)
Parameters: sorted takes three parameters from which two are optional.
- 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.
Python sorted() Function Example
Python3
print ( sorted ([ 4 , 1 , 3 , 2 ])) |
Output:
[1, 2, 3, 4]
Example 1: Sorting Python list using sorted()
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]
Example 2: Sorting different data types
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']
Example 3: Reverse sorting using Python sorted()
Sorting a string in lexicographically reverse order by setting reverse=True in 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
Example 4: Python sorted() lambda
Using sorted() inside Python lambda function
Python3
# import the module import functools # initializing string test_string = "geekforgeeks" # printing original string print ( "The original string : " + str (test_string)) # using sorted() + reduce() + lambda # Reverse Sort a String res = functools. reduce ( lambda x, y: x + y, sorted (test_string, reverse = True )) # print result print ( "String after reverse sorting : " + str (res)) |
Output:
The original string : geekforgeeks String after reverse sorting : srokkggfeeee
Python sorted() key
sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value. For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len() function as key, then the strings would be passed to len(), and the value it returns, i.e. the length of strings will be sorted. This means that the strings would be sorted based on their lengths instead
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']
Key can also take user-defined functions as its value for the basis of sorting.
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]
Sorting a list in ascending order:
Approach:In this example,1 we have a list called my_list that contains some integer values. We then use the sorted function to sort the list in ascending order, and assign the result to a new variable called sorted_list. The sorted function takes the iterable to be sorted as its first argument, and returns a new list that contains the sorted elements.
In this example 2, we have a string called my_string. We then use the sorted function to sort the characters in the string in ascending order, and assign the result to a new variable called sorted_string. The sorted function treats the string as an iterable of characters, and returns a new list that contains the sorted characters.
In this example3, we have a list of tuples called my_tuples, where each tuple contains an integer and a string. We then use the sorted function to sort the list based on the second element of each tuple (i.e., the string), and assign the result to a new variable called sorted_tuples. To achieve this, we pass a lambda function as the key argument to sorted, which extracts the second element of each tuple and uses it as the sorting key. The sorted function returns a new list that contains the sorted tuples.
Python3
# Sorting a list in ascending order my_list = [ 3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 , 5 ] sorted_list = sorted (my_list) print (sorted_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9] # Sorting a string in ascending order my_string = "hello, world!" sorted_string = sorted (my_string) print (sorted_string) # Output: [' ', '!', ',', 'd', 'e', 'h', 'l', 'l', 'o', 'o', 'r', 'w'] # Sorting a list of tuples based on a key function my_tuples = [( 1 , "one" ), ( 3 , "three" ), ( 2 , "two" ), ( 4 , "four" )] sorted_tuples = sorted (my_tuples, key = lambda x: x[ 1 ]) print (sorted_tuples) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] |
[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')]
Time complexity : O(n log n)
Auxiliary space : O(n)
Please Login to comment...