Python

sort() in list

Click for All Topics

sort() in list - Python

  • This method is used to sort the elements of a list in ascending order or descending order.
  • The .sort() method doesn’t return anything it modifies the original list.
  • The time complexity of this method is O(n log n) where n is the number of elements in the list.
  • You can also sort the list element on the basis of another function.
  • This method takes two optional arguments.

Syntax –

list.sort(reverse,key)

 

Parameters –

  • reverse → True/False (by default false), reverse=true sorts the list in descending.
  • key → a function which sets the basis, how the elements are to be sorted.
  • return → None(Doesn’t returns anything)

 

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]
				
			
  • In the above example, first we create a list with some elements and store it in my_list variable.
  • After creating my_list print the my_list on the output screen.
  • Then sort the my_list in ascending order by using the .sort() method.
  • Finally, print the sorted list on the output screen.

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)]