Python Lists Sort()
Using examples, we will discuss Python lists sort today in hopes that it will meet our learning objectives.
Using Python lists sort() function, you can sort a list ascendingly, descendingly, or based on the user’s preferences.
Python Lists Sort() Syntax:
Sort() has the following syntax:
The same can be achieved with Python’s built-in sorted() function.
sorted(list, key=..., reverse=...)
Confused? Don’t be Ptyhon Sort() changes the list directly and does not return a value, whereas sorted() does not change the list and returns the sorted list.
reverse: (Optional), if reverse=True, the list will be sorted descending. Reverse is set to False by default
key Optional. Functions for specifying sorting criteria
The reverse keyword argument can be used to sort descending.
An optional reverse parameter can be passed to the sort() method.
The list is sorted in descending order when reverse is set to True.
The Country list in below example is sorted descending as follows:
Another Example – The Country list is sorted descending as follows:
Alphanumerically sort() the list
Python lists objects have a sort() method that, by default, sorts them alphanumerically, ascending:
The list should be sorted alphabetically as follows:
To sort the list numerically, See below example:
Custom Sort() Function
The keyword argument key = function can also be utilize to customize your own function.
The Python lists sort function returns a number that will be applied to sort the list (the lowest number comes first):
The numbers should be sorted according to how close it is to 44:
If you want a list in reverse order regardless of alphabet, what should you do?
By using the reverse() method, the elements are sorted in reverse order.
List items in reverse order:
Note: We will discuss how Python list copies will work in our next post Python lists copy
Case Insensitive Sort()
As default, Python’s sort() method is case-sensitive, resulting in capital letters being sorted before lowercase letters:
There can be unexpected results when case-sensitive sorting is utilized:
It is a useful thing that we can define built-in functions as a key to sort a list.
You can apply str.lower as a key function to sort case-insensitively:
Sort the list case-insensitively:
Why to Sort Python Lists ?
Sorting Python lists is crucial for efficient data organization and streamlined search and retrieval. Sorted lists make it easier to locate and access specific items, reducing search time compared to unsorted lists. Sorting enables the use of efficient search algorithms like binary search and plays a vital role in various operations like merging, deduplication, and ranking. Additionally, sorted lists enhance data visualization and analysis by creating meaningful representations and simplifying data manipulation tasks. Overall, sorting Python lists improves data handling, search efficiency, algorithmic implementations, and data analysis, leading to valuable insights.