Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in sorted manner, without modifying the original sequence.
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 server as a key or a basis of sort comparison.
- Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
x = [2, 8, 1, 4, 6, 3, 7]
print "Sorted List returned :",
print sorted(x)
print "\nReverse sort :",
print sorted(x, reverse = True)
print "\nOriginal list not modified :",
print 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]