object | iterable 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. |
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 ) . 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
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]
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)]
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.