20
DecSort in Python- An Easy Way to Learn
Sort in Python
Sort in Python is an important and flexible technique that allows you to structure your data. To put it another means, sort in Python simply involves organizing it into a certain format or order.
In this Python tutorial, we will learn what is sort in Python?, what is the List sort() method?, how to use the sort() method, the sorting of operator module in Python functions, the difference between the sort() and sorted() methods, and many more.
What is Sort in Python?
Sort in Python is a common operation in programming languages. It involves arranging elements of a list or other iterable types in a specific order. Let's understand this method in some key points:
- Python provides two main sorting methods: sorted() and sort().
- The sorted() method is used to return a new sorted list.
- The sort() method is used to sort a list in place.
- The key parameter allows for custom sorting by defining a function that determines the sort order.
- Sorting in reverse order can be done by setting the reverse parameter to True, enabling descending-order sorting.
- Python's sorting is stable, which means that it keeps the order of elements equal based on the sorting criterion.
Read More |
Python Career Guide: Is it worth learning in 2025? |
10 Python Developer Skills You Must Know in 2025 |
Python Developer Roadmap: How to Become a Python Developer? |
What is the List sort() Method?
The sort() method in Python sorts the elements of a list in place, meaning it rearranges the original Python list in ascending or descending order according to the specified criteria. This method does not return a new list but rather modifies the existing one.
Syntax
list_name.sort(reverse=..., key=... )
Important points should be remembered here:
- list_name: Name of the list you are operating with.
- sort(): method of arranging elements in a list either in ascending or descending order and accepting two parameters.
- reverse: It is a boolean (True or False) value parameter used to arrange a list in ascending or descending order. The default value is False.
- The default value is false, which means it arranges the list in ascending order.
- If we set reverse to true, the list will be arranged in descending order.
- Key: It requires a function or method that specifies any particular sorting criteria you may have.
Note- sort() function returns None, indicating that there is no return value because it only updates the original list. It doesn't return a new list. |
1. Sorting a List in Ascending Order
Example
# Defining a list of a numbers
my_Num = [10, 4, 6, 14, 18, 7, 94, 100, 34]
#sorting the list in-place in ascending order
my_Num.sort()
#print the sorted list
print(my_Num)
Output
[4, 6, 7, 10, 14, 18, 34, 94, 100]
Explanation
- We have declared a list of my_Num with numbers.
- Use the sort() method, which prints the list in ascending order.
Example- Sorting a List of String Values in Alphabetical Ascending Order.
# a list of strings
family_mem = ["Raghav", "John","Anvadya", "Sam"]
#sort list in-place in alphabetical order
family_mem.sort()
#print modified list
print(family_mem)
Output
['Anvadya', 'John', 'Raghav', 'Sam']
Explanation
- We declare a list of family_mem with string values.
- We use sort() and print the original list in alphabetical ascending order.
2. Sorting a List in Descending Order
Example
# Defining a list of positive integer numbers
my_numb = [10, 8, 3, 24, 37, 7, 13, 99, 52]
#sorting list in-place in descending order
my_numb.sort(reverse=True)
#print modified list
print(my_numb)
Output
[99, 52, 37, 24, 13, 10, 8, 7, 3]
Explanation
- We declare a list of my_numb with positive integer numbers.
- We call the sort() method with (reverse=True) that prints the list in descending order.
3. Sorting With Custom Keys
Example
# declaring a list of string value
languages = ["Python", "Swift","Java", "C", "Go"]
#Assigning len() function to key parameter
languages.sort(key=len)
print(languages)
Output
['c', 'Go', 'Java', 'Swift', 'Python']
Explanation
- We have declared a list of languages that contain string values.
- In this languages. sort(key=len) line, we assign len() function to key parameter that prints the result in ascending order according to the length of the string values.
Sorting with Operator Module Functions
Python's operator module provides a collection of efficient functions that correspond to conventional operators. These functions can be used as the primary parameter in sorting operations to achieve more sophisticated sorts with simpler syntax. Here are some common functions for the operator module:
- operator.itemgetter()
- operator.attrgetter()
- operator.methodcaller()
1. operator.itemgetter()
The operator.itemgetter() function is used to sort a list based on specific item in a list of tuples or dictionaries. It allows you to sort by multiple fields by specifying multiple indices.
Example
import operator
# List of tuples
students = [("Aman", 90), ("Ankita", 80), ("Rajesh", 95)]
# Sort by the second element (the score)
sorted_students = sorted(students, key=operator.itemgetter(1))
print(sorted_students)
Output
[('Ankita', 80), ('Aman', 90), ('Ankita', 95)]
Explanation
- We import the operator module and declare a list of tuples name students.
- sorted_students = sorted(students, key=operator.itemgetter(1)) line, we assign operator.itemgetter() function in key parameter and prints the results.
2. operator.attrgetter()
The operator.attrgetter() is used to sort objects based on their attributes, providing a straightforward method to sort by specific properties. It also supports handling nested attributes, which is particularly useful for managing complex object structures.
Example
import operator
# Define a class with attributes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# List of Person objects
people = [Person("Aman", 30), Person("Ram", 25), Person("Ankita", 35)]
# Sort by the 'age' attribute
sorted_people = sorted(people, key=operator.attrgetter('age'))
print([person.name for person in sorted_people])
Output
['Ram', 'Aman', 'Ankita']
Explanation
In this example,
- We have defined a class Person with attributes and a list of name people that contains Person objects.
- sorted_people = sorted(people, key=operator.attrgetter('age')) line, we assign operator.attrgetter() operator in key parameter and prints the results.
3. operator.methodcaller()
The operator.methodcaller() is used for sorting elements based on the result of calling a specified method on each element.
Example
import operator
# List of strings
words = ["banana", "apple", "cherry"]
# Sort by the length of each string
sorted_words = sorted(words, key=operator.methodcaller('len'))
print(sorted_words)
Output
['apple', 'banana', 'cherry']
Explanation
- We have declared a list of words that contains the string values.
- sorted_words = sorted(words, key=operator.methodcaller('len')) line, we assign operator.methodcaller() with len() function in key parameter and print the results.
Difference Between sort() and sorted()
The sort() and sorted() methods are both used to sort the elements in a list. But they have some differences between them that are:
Features | sort() Method | sorted() Method |
Type | It is the method of listing objects | It is a built-in function |
Return Value | It provides none (modifies the list in place) | It provides a new sorted list |
Modifies Original | Yes | No |
Usage | Used when you want to sort a list in place | Used when you need a new sorted list without altering the original |
Performance | Generally faster for large lists since it sorts in place | Slightly slower due to the creation of a new list |
Read More |
Python Developer Salary |
Top 50+ Python Interview Questions and Answers |
Python Features: A Comprehensive Guide for Beginners |