Python list sort()
method in python is used to sort the elements of a list in ascending order by default.
It allows you to neatly organize elements within a list either in ascending or descending order, providing you with a versatile and efficient tool for data manipulation.
In this article, we will deeply understand sort()
method with practical examples.
Python list sort() syntax
Syntax of the sort()
method is as follows:
list_name.sort()
Here, list_name is the name of the list that you want to sort. sort()
will sort the elements of list in ascending order by default.
If the list is of strings, then it will sort in alphabetic order of elements. Example,
numbers = [4,5,2,6,3] numbers.sort() print(numbers) # Output: [2,3,4,5,6] fruits = ['guava','banana','apple'] fruits.sort() print(fruits) # Output: ['apple', 'banana', 'guava']
Note that sort()
will sort the list inline, meaning it will modify the original list.
Python list sort() parameters
sort()
does not take any parameters by default. But it supports following 2 optional parameters
1. reverse
By default, the reverse
parameter is set to False
, which sorts the list in ascending order.
Now when you want to sort a list in descending order using the sort()
method, you can set the reverse
parameter to True
.
The syntax for sorting a list in descending order is as follows:
list_name.sort(reverse=True)
Example of sorting a list in descending order is below
# Sorting list in descending order numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] numbers.sort(reverse=True) print(numbers)
2. key
sort()
method in python has an optional parameter key
that allows you to specify a function to customize the sorting order.
The syntax for using the key
parameter is as follows:
list_name.sort(key=custom_function)
Here, custom_function is the function that you define to determine the sorting order.
For example, you can sort a list of strings based on their lengths by defining a custom function that returns the length of each string.
This gives you more flexibility in how the elements are sorted, allowing for more complex sorting operations.
Below is an example of key parameter to sort list elements in ascending order of their lengths.
# Sorting a list of strings by their length fruits = ['apple', 'banana', 'cherry', 'date'] fruits.sort(key=len) print(fruits) # Output: ['date', 'apple', 'banana', 'cherry']
Understanding the key function
The key
function is a callable that takes an iterable element as an argument and returns a value that will be used for sorting.
It allows you to customize the sorting process based on your specific requirements.
The key function is applied to each element in the list before comparing them for sorting.
Following is example of custom function that sorts a list of tuples on the basis of increasing order of the sum of each tuple element.
# Sorting a list of tuples by the sum of their elements numbers = [(3, 1), (1, 2), (2, 3)] numbers.sort(key=lambda x: sum(x)) print(numbers) # Output: [(1, 2), (3, 1), (2, 3)]
Function that is supplied to key
is a lambda function, which is an anonymous function defined inline.
It takes one argument x
(which represents each tuple in numbers
) and returns the sum of the elements in the tuple x
.
sum()
is a built in python function that calculates the sum of the elements in each tuple x
.
Sorting list of objects with key
You can also sort a list of objects by providing custom function to key
parameter of sort()
function as shown below.
# Sorting a list of dictionaries by a specific key people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}] people.sort(key=lambda x: x['age']) print(people) # Output: [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
Sorting by Multiple Criteria
To sort a list by multiple criteria, you can again use the key
parameter in the sort()
method to define a custom sorting function that considers multiple attributes of the elements being sorted. Example,
# Sorting a list of dictionaries by 'age' and then 'name' data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}] data.sort(key=lambda x: (x['age'], x['name'])) print(data)
sort() Best Practices
Unlike the sorted()
function, which returns a new sorted list without modifying the original list, the sort()
method sorts the list in place.
When using sort()
, it is important to remember that the original list will be altered.
Therefore, if you need to preserve the original order of the list, it is better to use sorted()
to create a sorted copy of the list.
# Example of using sort() method numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] numbers.sort() print(numbers)
sort() versus sorted()
If you require a sorted copy of a list but do not want to modify the original list, sorted()
is the appropriate choice.
On the other hand, if you want to sort the list in place and do not need to preserve the original order, then sort()
is the method to use.
Understanding the difference between these two approaches will help you choose the right method for your specific needs.
Performance considerations
Versus the sorted()
function which creates a new sorted list, the sort()
method rearranges the elements in place which can be more efficient in terms of memory usage.
However, it is imperative to consider the trade-off between speed and memory consumption when deciding between the two methods.
Additionally, for large datasets, the performance difference between sort()
and sorted()
may become more significant, so choosing the right method is crucial for optimal performance.
For instance, if you have a small list that needs to be sorted and preserving the original order is not a concern, using the sort()
method can be more efficient and convenient.
However, when working with larger datasets or when you need to maintain the original list unchanged, opting for the sorted()
function may be a better choice to ensure both performance and data integrity.
Pitfalls and Common Issues
Your python code may encounter some common issues when using the sort()
method for lists.
One common pitfall is trying to sort a list with a mix of different data types, which can lead to TypeError exceptions.
Another issue is mistakenly assuming that sort()
will return a new sorted list when in fact it sorts the list in place, modifying the original list.
Conclusion
sort()
method in python allows you to sort a list either in ascending or descending order.
By default, sort()
arranges the elements in ascending order, but you can use the reverse
parameter to sort in descending order.
Additionally, you can use the key
parameter to specify a function that determines the sorting criteria.
Understanding how to use sort()
effectively can help you efficiently organize and manipulate lists in python.