sort() method in Python sort the elements of a list in ascending or descending order. It modifies the original list in place, meaning it does not return a new list, but instead changes the list it is called on. Example:
Python
a = [5, 3, 8, 1, 2]
a.sort()
print(a)
a.sort(reverse=True)
print(a)
Output[1, 2, 3, 5, 8]
[8, 5, 3, 2, 1]
Explanation:
- a.sort() sorts a in ascending order.
- a.sort(reverse=True) sorts a in descending order.
Syntax of sort()
list.sort(reverse=False, key=None, m=None)
Parameters:
- reverse (optional): If True, sorts in descending order; default is False for ascending order.
- key (optional): A function for custom sorting conditions.
- m (optional): A custom parameter for additional sorting behavior, like a threshold.
Returns: This method returns None as it does not create a new list, it simply modifies the original list in place.
Examples of sort()
Example 1: In this example, we arrange a list of strings in alphabetical (lexicographical) order.
Python
a = ["banana", "apple", "cherry"]
a.sort()
print(a)
Output['apple', 'banana', 'cherry']
Explanation: a.sort(reverse=True) sorts the list in descending order, from Z to A, based on their Unicode code points.
Example 2: In this example, we sort a list of strings by their length using the key parameter of the sort() method. By passing the built-in len function, the strings are sorted in ascending order based on length.
Python
a = ["sun", "moonlight", "sky"]
a.sort(key=len)
print(a)
Output['sun', 'sky', 'moonlight']
Explanation: a.sort(key=len) sorts the list based on the length of each string, arranging them in ascending order of their lengths.
Example 3: In this example, we sort a list of dictionaries by the value of the "age" key using the key parameter of the sort() method.
Python
d = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
d.sort(key=lambda person: person["age"])
print(d)
Output[{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
Explanation: d.sort(key=lambda person: person["age"]) sorts the list of dictionaries by the "age" key in ascending order. The lambda function extracts the age from each dictionary for comparison.
Example 4: In this example, we sort a list of tuples by the second element (age) using the key parameter with a lambda function, sorting the list in ascending order by age.
Python
a = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]
a.sort(key=lambda x: x[1])
print(a)
Output[('Charlie', 22), ('Alice', 25), ('Bob', 30)]
Explanation: a.sort(key=lambda x: x[1]) sorts the list of tuples by the second element age in ascending order. The lambda function accesses the second element of each tuple for comparison.
Difference between sorted() and sort() function in Python
Understanding the difference between sorted() and sort() helps you choose the right tool for your needs. Both sort elements but differ in memory usage, stability, and compatibility. Let’s break it down in the following table.
Feature | sorted() | sort() |
---|
Return Type | Returns a new sorted list | Sorts the list in place |
---|
Order | Can specify ascending/descending | Default is ascending |
---|
Applicable to | Any iterable (not just lists) | Only lists |
---|
Stability | Stable (maintains relative order) | May not be stable |
---|
Memory Usage | Requires extra memory | Sorts in place, no extra memory |
---|
Key Parameter | Supports key for custom sorting | Supports key for custom sorting |
---|
Time Complexity | O(n log n) | O(n log n) |
---|
Related Articles
Similar Reads
numpy.sort() in Python
numpy.sort() : This function returns a sorted copy of an array. Parameters : arr : Array to be sorted. axis : Axis along which we need array to be started. order : This argument specifies which fields to compare first. kind : [âquicksortâ{default}, âmergesortâ, âheapsortâ]Sorting algorithm. Return :
1 min read
Counting Sort - Python
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
6 min read
Insertion Sort - Python
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list.Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the le
3 min read
Comb Sort - Python
Comb Sort is an improvement over Bubble Sort, and it aims to eliminate the problem of small values near the end of the list, which causes Bubble Sort to take more time than necessary. Comb Sort uses a larger gap for comparison, which gradually reduces until it becomes 1 (like the gap in Shell Sort).
2 min read
Python MongoDB - Sort
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with
2 min read
Python sorted() Function
sorted() function returns a new sorted list from the elements of any iterable like (e.g., list, tuples, strings ). It creates and returns a new sorted list and leaves the original iterable unchanged. Let's start with a basic example of sorting a list of numbers using the sorted() function.Pythona =
3 min read
Python | Numpy matrix.sort()
With the help of matrix.sort() method, we are able to sort the values in a matrix by using the same method. Syntax : matrix.sort() Return : Return a sorted matrix Example #1 : In this example we are able to sort the elements in the matrix by using matrix.sort() method. Python3 1=1 # import the impor
1 min read
Shell Sort - Python
Shell Sort is an advanced version of the insertion sort algorithm that improves its efficiency by comparing and sorting elements that are far apart. The idea behind Shell Sort is to break the original list into smaller sublists, sort these sublists, and gradually reduce the gap between the sublist e
2 min read
Radix Sort - Python
Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. Rather than comparing elements directly, Radix Sort distributes the elements into buckets based on each digitâs value. By
3 min read
TreeMap in Python
TreeMap is a data structure that stores key-value pairs in a sorted order based on the keys. In Python, there is no direct built-in implementation of a TreeMap, but the sortedcontainers module provides a SortedDict class that works similarly to a TreeMap. TreeMap is implemented using a balanced bina
2 min read