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.
Python
# Initializing a list
a = [5, 1, 5, 6]
# Sort modifies the given list
a.sort()
print(a)
b = [5, 2, 9, 6]
# Sorted does not modify the given list
# and returns a different sorted list
bs = sorted(b)
print(b)
print(bs)
Output[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.
Python Sorting Methods
Python sort()
Method
The sort()
method sorts the list in place and modifies the original list. By default, it sorts the list in ascending order.
Python
# Initializing a list
a = [5, 2, 9, 1, 5, 6]
# Sorting the list in ascending order
a.sort()
print("Sorted list (ascending):", a)
a.sort(reverse=True)
print("Sorted list (descending):", a)
OutputSorted list (ascending): [1, 2, 5, 5, 6, 9]
Sorted list (descending): [9, 6, 5, 5, 2, 1]
Python sorted()
Function
Python 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.
Python
# Initializing a list
a = [5, 2, 9, 1, 5, 6]
# Sorting the list in descending order
sa = sorted(a)
print("Sorted list (ascending):", sa)
sa = sorted(a, reverse=True)
print("Sorted list (descending):", sa)
OutputSorted list (ascending): [1, 2, 5, 5, 6, 9]
Sorted list (descending): [9, 6, 5, 5, 2, 1]
Sorting Other Containers :
- Sorting a tuple: The
sorted()
function converts the tuple into a sorted list of its elements. - Sorting a set: Since sets are unordered,
sorted()
converts the set into a sorted list of its elements. - Sorting a string: This will sort the characters in the string and return a list of the sorted characters.
- Sorting a dictionary: When a dictionary is passed to
sorted()
, it sorts the dictionary by its keys and returns a list of the keys in sorted order. - Sorting a list of tuples: The list of tuples is sorted primarily by the first element of each tuple, and secondarily by the second element if the first ones are identical.
Python
# Sorting a tuple
a = (10, 12, 5, 1)
print(sorted(a))
# Sorting a set
s = {'gfg', 'course', 'python'}
print(sorted(s))
# Sorting a string
st = 'gfg'
print(sorted(st))
# Attempting to sort a dictionary (it will sort the keys)
d = {10: 'gfg', 15: 'ide', 5: 'course'}
print(sorted(d))
# Sorting a list of tuples
l = [(10, 15), (1, 8), (2, 3)]
print(sorted(l))
Output[1, 5, 10, 12]
['course', 'gfg', 'python']
['f', 'g', 'g']
[5, 10, 15]
[(1, 8), (2, 3), (10, 15)]
Sorting User Defined Object
Example 1: Using a Separate Method
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.
Python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def myFun(p):
return p.x
l = [Point(1, 15), Point(10, 5), Point(3, 8)]
l.sort(key=myFun)
for i in l:
print(i.x, i.y)
Example 2: Using a __lt__ Method
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.
Python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return self.x < other.x
l = [Point(1, 15), Point(10, 5), Point(3, 8)]
l.sort()
for i in l:
print(i.x, i.y)
Sorting with Custom Criteria
Sorting Based on Absolute Values
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.
Python
a = [1, -5, 10, 6, 3, -4, -9]
# Sorting by absolute values in descending order
sa = sorted(a, key=abs, reverse=True)
print("Sorted by absolute values:", sa)
OutputSorted by absolute values: [10, -9, 6, -5, -4, 3, 1]
Custom Sorting with Lambda Functions
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:
Python
# List of tuples
a = [(1, 'one'), (3, 'three'), (2, 'two')]
# Sorting by the second element of each tuple
sa = sorted(a, key=lambda x: x[1])
print("Sorted by second element:", sa)
OutputSorted 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()
.
Time Complexity
sort()
and sorted()
: Both have a time complexity of O(n log n).
Similar Reads
Sort mixed list in Python
Sometimes, while working with Python, we can have a problem in which we need to sort a particular list that has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let's discuss certain ways in which this problem can be solved. Method #1: Using sort(
4 min read
Python | Sort lists in tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to sort the tuples which constitutes of lists and we need to sort each of them. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + sorted() + generator expression This task ca
4 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Python - Nearest K Sort
Given a List of elements, perform sort on basis of its distance from K. Input : test_list = [6, 7, 4, 11, 17, 8, 3], K = 10 Output : [11, 8, 7, 6, 4, 17, 3] Explanation : 11-10 = 1; < 10 - 8 = 2 .. Ordered by increasing difference. Input : test_list = [6, 7, 4, 11], K = 10 Output : [11, 7, 6, 4]
4 min read
Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l
7 min read
Python | Alternate Sort in String list
Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
2 min read
Python - Sort from Kth index in List
Given a list of elements, perform sort from Kth index of List. Input : test_list = [7, 3, 7, 6, 4, 9], K = 2 Output : [7, 3, 4, 6, 7, 9] Explanation : List is unsorted till 3 (1st index), From 2nd Index, its sorted. Input : test_list = [5, 4, 3, 2, 1], K= 3 Output : [5, 4, 3, 1, 2] Explanation : Onl
3 min read
Python - Sort by Units Digit in List
Given a Integer list, sort by unit digits. Input : test_list = [76, 434, 23, 22342] Output : [22342, 23, 434, 76] Explanation : 2 < 3 < 4 < 6, sorted by unit digits. Input : test_list = [76, 4349, 23, 22342] Output : [22342, 23, 76, 4349] Explanation : 2 < 3 < 6 < 9, sorted by unit
7 min read
Sort Numeric Strings in a List - Python
We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
2 min read
Python | Sort each String in String list
Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
4 min read