Python list sort ()

Python list sort() function is used to sort a list in ascending, descending or user defined order.

To sort the list in ascending order

List_name.sort()
This will sort the given list in ascending order.

This function is used to sort list of integers, floating point number, string and others.

numbers = [8, 5, 7, 9] 
  
# Sorting list of Integers in ascending 
numbers.sort() 
  
print(numbers)

Output

[5, 7, 8, 9]

Example 2:

strs = ["wikitechy", "code", "ide", "practice"] 
  
# Sorting list of Integers in ascending 
strs.sort() 
  
print(strs)

Output

['code', 'ide', 'practice', 'wikitechy']

To sort the list in descending order

Example:

list_name.sort(reverse=True)
This will sort the given list in descending order
numbers = [8, 5, 7, 9] 
  
# Sorting list of Integers in descending 
numbers.sort(reverse = True) 
  
print(numbers)

Output

[9, 8, 7, 5]

Sorting user using user defined order

list_name.sort(key=, reverse=) – it sorts according to user’s choice

Example

# Python program to demonstrate sorting by user's 
# choice 
  
# function to return the second element of the 
# two elements passed as the parameter 
def sortSecond(val): 
    return val[1]  
  
# list1 to demonstrate the use of sorting  
# using using second key  
list1 = [(1, 2), (3, 3), (1, 1)] 
  
# sorts the array in ascending according to  
# second element 
list1.sort(key = sortSecond)  
print(list1) 
  
# sorts the array in descending according to 
# second element 
list1.sort(key = sortSecond, reverse = True) 
print(list1)

Output

[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]

Post navigation

Python String split()

Python split() method splits the string into a comma-separated list. Python String Python string is that…

If you like this post you might alo like these

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO