Built-in function 'sorted' takes an iterable as argument and return a new sorted list from the items in iterable.
Signature
sorted(iterable, *, key=None, reverse=False)
Example1: To sort the list in ascending order.
ascending_order_list = sorted(my_list)
Example 2: To sort the list in descending order.
descending_order_list = sorted(my_list, reverse=True)
Find the below working application.
sort_list.py
my_list = [2, 1, 3, 8, 4, 9, 5]
ascending_order_list = sorted(my_list)
descending_order_list = sorted(my_list, reverse=True)
print('my_list : ', my_list)
print('ascending_order_list : ', ascending_order_list)
print('descending_order_list : ', descending_order_list)
Output
my_list : [2, 1, 3, 8, 4, 9, 5] ascending_order_list : [1, 2, 3, 4, 5, 8, 9] descending_order_list : [9, 8, 5, 4, 3, 2, 1]
No comments:
Post a Comment