
👉Python sort() Method Explained with Examples
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.
👉Syntax of sort() Method in Python
python
list.sort(key=…, reverse=…)
👉Python sort Parameters:
- key (Optional): Defines a sorting criterion using a function.
- reverse (Optional): Set to True for descending order; default is False (ascending order).
👉Sorting Lists in Ascending Order
By default, the sort() method sorts elements in ascending order.
Example:
python
base_list = [“Google”, “Reliance”, “Syntax”, “Content”]
base_list.sort()
print(“Sorted list:”, base_list)
Output: [‘Content’, ‘Google’, ‘Reliance’, ‘Syntax’]
👉Sorting Lists in Descending Order
For descending order sorting, set the reverse parameter to True.
Example:
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.
👉Sorting a List of Tuples Using sort()
You can sort tuples using a custom function or lambda expression.
Example with Custom Function:
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)]
Example with Lambda Expression:
python
base_list.sort(key=lambda x: x[2], reverse=True)
print(“Sorted tuple list using lambda:”, base_list)
👉Sorting by String Length Using len()
The len() function can be used as the key parameter to sort based on item length.
Example:
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’]
👉Using User-defined Functions for Sorting
A user-defined function can customize the sorting criteria.
Example:
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)
👉Difference Between sort() and sorted()
Feature | sort() | sorted() |
Modifies Original List | Yes | No (creates a new list) |
Returns Value | None | New sorted list |
Suitable For | Non-iterable data | Iterable data (strings, tuples, etc.) |
Example for Comparison:
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]