English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
sorted() function returns a sorted list in an iterative manner.
sorted() function returns a sorted list in a specific order (AscendingorDescending) to sort the given iterable elements.
The syntax of sorted() is:
sorted(iterable, key=None, reverse=False)
sorted() can use up to three parameters:
iterable-Sequence(String,Tuple,List) or set(Set,Dictionary,Frozen set) or any other iterator.
reverse (optional) -If set to True, the sorted list will be reversed (or sorted in descending order). If not provided, the default is False.
key (optional) -Used as a function for sorting comparison key. The default is None.
# Vowel list py_list = ['e', 'a', 'u', 'o', 'i'] print(sorted(py_list)) # string py_string = 'Python' print(sorted(py_string)) # Vowel tuple py_tuple = ('e', 'a', 'u', 'o', 'i') print(sorted(py_tuple))
Output result
['a', 'e', 'i', 'o', 'u'] ['P', 'h', 'n', 'o', 't', 'y'] ['a', 'e', 'i', 'o', 'u']
Note:The list also hassort()Method, which operates in the same way as sort(). The only difference is that the sort() method does not return any value and changes the original list.
The sorted() function accepts a reverse parameter as an optional argument.
Set reverse = True to sort the iterable in reverse order.
# set py_set = {'e', 'a', 'u', 'o', 'i'} print(sorted(py_set, reverse = True)) # dictionary py_dict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5} print(sorted(py_dict, reverse = True)) # frozen set frozen_set = frozenset(('e', 'a', 'u', 'o', 'i')) print(sorted(frozen_set, reverse = True))
Output result
['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a']
If you want to sort using your own implementation, then sort() also accepts a key function as an optional parameter.
You can sort the given iterable according to the result of the key function.
sorted(iterable, key=len)
len() is a built-in function in Python, used to calculate the length of an object.
The list is sorted according to the length of the elements (from the lowest to the highest count).
# Sort by the second element def take_second(elem): return elem[1] # Random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # Key sorted list sorted_list = sorted(random, key = take_second) # Print list print('Sorted list:', sorted_list)
Output result
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]