![]() |
VOOZH | about |
Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.
[1, 5, 5, 6] [5, 2, 9, 6] [2, 5, 6, 9]
This article will cover the basics of sorting lists in Python, including built-in functions, custom sorting, and sorting based on specific criteria.
Table of Content
sort() MethodThe sort() method sorts the list in place and modifies the original list. By default, it sorts the list in ascending order.
Sorted list (ascending): [1, 2, 5, 5, 6, 9] Sorted list (descending): [9, 6, 5, 5, 2, 1]
sorted() FunctionPython sorted() function returns a sorted list. It is not only defined for the list and it accepts any iterable (list, tuple, string, etc.). It does not modify the given container and returns a sorted version of it.
Sorted list (ascending): [1, 2, 5, 5, 6, 9] Sorted list (descending): [9, 6, 5, 5, 2, 1]
sorted() function converts the tuple into a sorted list of its elements.sorted() converts the set into a sorted list of its elements.sorted(), it sorts the dictionary by its keys and returns a list of the keys in sorted order.[1, 5, 10, 12] ['course', 'gfg', 'python'] ['f', 'g', 'g'] [5, 10, 15] [(1, 8), (2, 3), (10, 15)]
This code defines a Point class with an initializer that sets the x and y coordinates for point objects. The myFun function takes a point object and returns its x coordinate. A list l of Point objects is created, and then sorted based on their x values using the myFun function as the key in the sort method. Finally, it prints out the x and y coordinates of each Point in the sorted list.
1 15 3 8 10 5
This version defines the __lt__ method within the Point class and includes the necessary return statement, which compares the x attribute of the instances. Now when you call l.sort(), Python will use this __lt__ method to determine the order of Point objects in the list based on their x values. This will sort the points in ascending order by their x coordinates, and the print output will reflect that order.
1 15 3 8 10 5
Sometimes you may want to sort numbers based on their absolute values while preserving their original signs. You can do this by using the key parameter in both the sort() method and the sorted() function.
Sorted by absolute values: [10, -9, 6, -5, -4, 3, 1]
You can use lambda functions to define custom sorting logic. For example, if you want to sort a list of tuples based on the second element:
Sorted by second element: [(1, 'one'), (3, 'three'), (2, 'two')]
When sorting lists, the choice between sort() and sorted() may depend on whether you want to maintain the original list. The sort() method is generally faster since it sorts the list in place. However, if you need to keep the original order, use sorted().
sort() and sorted(): Both have a time complexity of O(n log n).