sorted()

sorted(object,reverse,key) Returns sorted list of input iterable object
objectiterable Object to be sorted .
reverse (Optional ) if set to True then reverse or descending order is used.
key (Optional ) default is None, Function used for sorting each element.
Original iterable object is not chagned.
Using a numeric list
my_list=[12,3,8,7,14]
print(sorted(my_list))
#print(my_list)
Output
[3, 7, 8, 12, 14]
You can check the original list also ( unchanged ) .

Using a list of string
my_list=['Orange','Banana','Apple','Mango']
print(sorted(my_list))
Output
['Apple', 'Banana', 'Mango', 'Orange']
Using a string
my_str='plus2net'
print(sorted(my_str))
Output
['2', 'e', 'l', 'n', 'p', 's', 't', 'u']

reverse=True ( Optional )

We will change the order of sorting by adding reverse=True
my_list=['Orange','Banana','Apple','Mango']
print(sorted(my_list,reverse=True))
Output
['Orange', 'Mango', 'Banana', 'Apple']
Using numbers
my_list=[12,3,8,7,14]
print(sorted(my_list,reverse=True))
Output
[14, 12, 8, 7, 3]

Using key ( Optional )

We can add key to use customized sorting function.
Let us arrange in the order of length of the elements ( we will use len function )
my_list=['Three','One','Seven','thirtyfive','Two']
print(sorted(my_list,key=len))
Output ( in the order of increasing length of element )
['One', 'Two', 'Three', 'Seven', 'thirtyfive']
We can add reverse=True to get in descending order
print(sorted(my_list,key=len,reverse=True))
Output
['thirtyfive', 'Three', 'Seven', 'One', 'Two']
We can use user defined function to get sorting order based on the 2nd element of tuple.
my_list=[(3,5),(2,1),(8,4),(3,7)]
def my_sort(my_data):
    return my_data[1]
print(sorted(my_list,key=my_sort))
Output ( in the increasing order of each 2nd element )
[(2, 1), (8, 4), (3, 5), (3, 7)]

All Built in Functions in Python setattr() delattr() getattr()


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer