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
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
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
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
Python List sort() Method The sort() method in Python is a built-in function that allows us to sort the elements of a list in ascending or descending order and it modifies the list in place which means there is no new list created. This method is useful when working with lists where we need to arranged the elements in a spec
3 min read
Python | Inverse Sorting String Sometimes, while participating in a competitive programming test, we can be encountered with a problem in which we require to sort a pair in opposite orders by indices. This particular article focuses on solving a problem in which we require to sort the number in descending order and then the String
3 min read
Sort a Pandas Series in Python Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. Now, Let's see a program to sort a Pandas Series. For sorting a pandas series the Series.sort_values() method is used. Syntax: Se
3 min read
Python | Pandas Index.sort_values() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.sort_values() function is used to sort the index values. The function ret
2 min read
Python Program for Counting Sort Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Python3 # Python program for counting sort
2 min read