---Advertisement---

Python sort() Method Explained with Best Examples: Sorting Lists, Tuples, and Custom Functions 2025

By Bhavani

Updated On:

---Advertisement---
Python sort

Python sort: The sort() method in Python is a powerful tool for sorting lists efficiently. It modifies the original list instead of creating a new one. Python sort This method is widely used for sorting numeric data, strings, and even tuples.

python

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

  • key (Optional): Defines a sorting criterion using a function.
  • reverse (Optional): Set to True for descending order; default is False (ascending order).

By default, the sort() method sorts elements in ascending order.

python

base_list = [“Google”, “Reliance”, “Syntax”, “Content”]

base_list.sort()

print(“Sorted list:”, base_list)

Output: [‘Content’, ‘Google’, ‘Reliance’, ‘Syntax’]


For descending order sorting, set the reverse parameter to True.

python

base_list = [100, 600, 400, 8000, 50]

base_list.sort(reverse=True)

print(“Descending order sorted list:”, base_list)

Output: [8000, 600, 400, 100, 50]

Note: Ensure “True” starts with an uppercase T to avoid errors.


You can sort tuples using a custom function or lambda expression.

python

base_list = [(‘Alto’, 2020, 500), (‘MSFT’, 2022, 300), (‘Software Moji Moji’, 2019, 1070)]

def get_key(element):

    return element[2]

base_list.sort(key=get_key, reverse=True)

print(“Sorted tuple list:”, base_list)

Output: [(‘Software Moji Moji’, 2019, 1070), (‘Alto’, 2020, 500), (‘MSFT’, 2022, 300)]

python

base_list.sort(key=lambda x: x[2], reverse=True)

print(“Sorted tuple list using lambda:”, base_list)


The len() function can be used as the key parameter to sort based on item length.

python

base_list = [“Alto”, “Software Moji Moji”, “Python”, “Google”, “Java”]

base_list.sort(key=len)

print(“Sorted by length:”, base_list)

Output: [‘Alto’, ‘Java’, ‘Python’, ‘Google’, ‘Software Moji Moji’]


A user-defined function can customize the sorting criteria.

python

base_list = [{‘Example’: ‘Python’, ‘year’: 2011}, {‘Example’: ‘Alto’, ‘year’: 2014}]

def get_year(element):

    return element[‘year’]

base_list.sort(key=get_year)

print(“Sorted by year:”, base_list)


Featuresort()sorted()
Modifies Original ListYesNo (creates a new list)
Returns ValueNoneNew sorted list
Suitable ForNon-iterable dataIterable data (strings, tuples, etc.)

python

base_list = [11, 10, 9, 8, 7, 6]

sorted_list = sorted(base_list)

print(“Sorted list:”, sorted_list)  # [6, 7, 8, 9, 10, 11]

base_list.sort()

print(“Modified original list:”, base_list)  # [6, 7, 8, 9, 10, 11]

Python List

Download Python

Leave a Comment

Index