The sorted() method sorts the elements of a given iterable in a specific order - Ascending or Descending.
The syntax of sorted() method is:
sorted(iterable[, key][, reverse])
sorted() takes two three parameters:
sorted() method returns a sorted list from the given iterable.
# vowels list pyList = ['e', 'a', 'u', 'o', 'i'] print(sorted(pyList)) # string pyString = 'Python' print(sorted(pyString)) # vowels tuple pyTuple = ('e', 'a', 'u', 'o', 'i') print(sorted(pyTuple))
When you run the program, the output will be:
['a', 'e', 'i', 'o', 'u'] ['P', 'h', 'n', 'o', 't', 'y'] ['a', 'e', 'i', 'o', 'u']
Note: A list also has sort() method which performs the same way as sorted(). Only difference being, sort() method doesn't return any value and changes the original list itself.
sorted() method accepts a reverse
parameter as an optional argument.
Setting reverse=True
sorts the iterable in the descending order.
# set pySet = {'e', 'a', 'u', 'o', 'i'} print(sorted(pySet, reverse=True)) # dictionary pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5} print(sorted(pyDict, reverse=True)) # frozen set pyFSet = frozenset(('e', 'a', 'u', 'o', 'i')) print(sorted(pyFSet, reverse=True))
When you run the program, the output will be:
['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a'] ['u', 'o', 'i', 'e', 'a']
If you want your own implementation for sorting, sorted() also accepts a key
function as an optional parameter.
Based on the results of the key function, you can sort the given iterable.
sorted(iterable, key=len)
Here, len is the Python's in-built function to count the length of an element.
The list is sorted based on the length of its each element, from lowest count to highest.
# take second element for sort def takeSecond(elem): return elem[1] # random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # sort list with key sortedList = sorted(random, key=takeSecond) # print list print('Sorted list:', sortedList)
When you run the program, the output will be:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal