Click for All Topics
.sort()
method doesn’t return anything it modifies the original list.Syntax –
list.sort(reverse,key)
Parameters –
Example 1-
my_list=[10,5,11,21,34,12,15,9,3,81]
print("Original list:",my_list)
my_list.sort()
print("Sorted original list:",my_list)
# Output -
# Original list: [10, 5, 11, 21, 34, 12, 15, 9, 3, 81]
# Sorted original list: [3, 5, 9, 10, 11, 12, 15, 21, 34, 81]
.sort()
method.Example 2- sort the list on the basis of alphabetical order
my_list=['Hello','Python', 'List', 'Sort','Method']
print("Original list:",my_list)
my_list.sort()
print("Sorted list:",my_list)
# Output -
# Original list: ['Hello', 'Python', 'List', 'Sort', 'Method']
# Sorted list: ['Hello', 'List', 'Method', 'Python', 'Sort']
Example 3- Sort the list in descending order
my_list=[11,23,54,45,41,10,13,75]
print("Original list:",my_list)
my_list.sort(reverse=True)
print("Sorted list in descending order:",my_list)
# Output -
# Original list: [11, 23, 54, 45, 41, 10, 13, 75]
# Sorted list in descending order: [75, 54, 45, 41, 23, 13, 11, 10]
Example 4- Sort the list on the basis of another function
my_list = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
print("Original list:",my_list)
# Sorting the list based on the sum of elements in each tuple
my_list.sort(reverse=True,key=sum)
print("Sorted list based on the sum of elements in each tuple:")
print(my_list)
# Output -
# Original list: [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
# Sorted list based on the sum of elements in each tuple:
# [(10, 11, 12), (7, 8, 9), (4, 5, 6), (1, 2, 3)]
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India