Elements in the tuple and list can be sorted using the sorted() function.
Syntax for sorted() function is:
sorted(sequence,key,reverse)
- sequence could be tuple or list whose elements need to be sorted
- key is input to the sorting algorithm
- iterable is the order - Ascending/Descending
The output of the sorted() is always a list type
#list declaration
num = [56,3,78,112,1,234,23,43,345,0]
#sorted() function used for ascending order
print(sorted(num))
#sorted() function used for descending order
print(sorted(num,reverse=True))
Output of the above code is,
[0, 1, 3, 23, 43, 56, 78, 112, 234, 345]
[345, 234, 112, 78, 56, 43, 23, 3, 1, 0]
-------------
#tuple declaration
num_1 = (56,3,78,112,1,234,23,43,345,0)
#sorted() function used for ascending order
print(sorted(num_1))
#sorted() function used for descending order
print(sorted(num_1,reverse=True))
Output of the above code is,
[0, 1, 3, 23, 43, 56, 78, 112, 234, 345]
[345, 234, 112, 78, 56, 43, 23, 3, 1, 0]
0 Comments