Skip to main content

Python: Sort List

It sorts the elements of a given list in a specific ascending or descending order.

1. Sort list in ascending order

Syntax:

List_name.sort()

Example: 

list_1 = [6,4,5,2,3,1]
list_1.sort()
print(list_1)

Output: [1, 2, 3, 4, 5]

2. Sort list in descending order

Syntax:

list_name.sort(reverse = True)

Example: 

list_1 = [6,4,5,2,3,1]
list_1.sort(reverse = True)
print(list_1)

Output: [6, 5, 4, 3, 2, 1]

3. Sort list using user defined order

It sorts according to user's choice.

Syntax:

list_name.sort(key=…, reverse=…)

Example: 

def sort_first(val):
    return val[1]

list_1 = [(1, 2), (3, 3), (1, 1)]
list_1.sort(key = sort_first) 
print(list_1)

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

Tags
Submitted by devanshi.srivastava on June 10, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.