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 = ["gpkumar", "code", "ide", "practice"] 

# Sorting list of Integers in ascending
strs.sort()

print(strs)

Output

['code', 'ide', 'practice', 'gpkumar']

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

Praveen Kumar

I am a fullstack web developer with a passion for SEO, creating stunning websites, and organic marketing. I am a perfectionist.

Post navigation