/    /  Python – Sorted

Python Sorted

In Python, we can sort the elements in the string, list or tuple in the ascending or descending order by using sorted() function. This function returns list of elements in an order.

Syntax:

sorted(iterable, key, reverse)


iterable is a sequence or a collection of elements in list or string or tuple.

Key is a function which serve as key or basis of sort comparison, it is optional parameter.

Reverse is a function which sort the elements in descending order, it is also an optional parameter.

Python code for sorting elements in different data types which returns list of the sorted elements.


Python Code:

#sorting the list 
number=[2,20,14,27,16,35,1,19,54,75]
num=sorted(number)
print(num)
#sorting the string
string="programming"
char=sorted(string)
print(char)
#sorting the tuple
tup=("v","a","p","f","n","k","c","m","s")
tupp=sorted(tup)
print(tupp)
#sorting the dictionary
dic={"c":6,"e":5,"b":2,"m":4,"l":1,"r":2}
dctn=sorted(dic)
print(dctn)
#sorting the set
name={"ross","joey","rachel","monica","chandler","phoebe"}
friends=sorted(name)
print(friends)


Output:

[1, 2, 14, 16, 19, 20, 27, 35, 54, 75]

[‘a’, ‘g’, ‘g’, ‘i’, ‘m’, ‘m’, ‘n’, ‘o’, ‘p’, ‘r’, ‘r’]

[‘a’, ‘c’, ‘f’, ‘k’, ‘m’, ‘n’, ‘p’, ‘s’, ‘v’]

[‘b’, ‘c’, ‘e’, ‘l’, ‘m’, ‘r’]

[‘chandler’, ‘joey’, ‘monica’, ‘phoebe’, ‘rachel’, ‘ross’]


We can sort the elements in descending order as discussed earlier by using reverse parameter in the sorted function.


Python Code:

number=[2,20,14,27,16,35,1,19,54,75]
num=sorted(number)
print(num)
revnum=sorted(number,reverse=True)
print(revnum)


Output:

[1, 2, 14, 16, 19, 20, 27, 35, 54, 75]

[75, 54, 35, 27, 20, 19, 16, 14, 2, 1]