Table of Contents
ToggleSorting a list in Python is a way to arrange the elements of the list in either ascending or descending order based on a defined criterion, such as numerical or lexicographical order.
This can be achieved using the built-in sorted() function or by calling the sort() method on the list itself, both of which modify the original list or return a new sorted list depending on the method used.
The Python sort() method is used to sort the elements of a list in place. This means that it modifies the original list and does not return a new list.
list_name.sort(key=None, reverse=False)
Where:
None.True, the list will be sorted in descending order. If False (default), the list will be sorted in ascending order.list1 = ['physics', 'Biology', 'chemistry', 'maths']
print("List before sort:", list1)
list1.sort()
print("List after sort:", list1)
Output:
List before sort: ['physics', 'Biology', 'chemistry', 'maths']
List after sort: ['Biology', 'chemistry', 'maths', 'physics']
list2 = [10, 16, 9, 24, 5]
print("List before sort:", list2)
list2.sort()
print("List after sort:", list2)
Output:
List before sort: [10, 16, 9, 24, 5]
List after sort: [5, 9, 10, 16, 24]
The sorted() function in Python is a built-in function used to sort the elements of an iterable (such as a list, tuple, or string) and returns a new sorted list, leaving the original iterable unchanged.
sorted(iterable, key=None, reverse=False)
Where:
None.True, the iterable will be sorted in descending order. If False (default), the iterable will be sorted in ascending order.numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Sorting in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)
Output:
[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
In Python, a callback function refers to a function that is passed as an argument to another function and is invoked or called within that function.
We can sort list items with a callback function by using the sorted() function or sort() function in Python. Both of these functions allow us to specify a custom sorting criterion using the key parameter, which accepts a callback function.
list1 = ['Physics', 'biology', 'Biomechanics', 'psychology']
print("List before sort:", list1)
list1.sort(key=str.lower)
print("List after sort:", list1)
Output:
List before sort: ['Physics', 'biology', 'Biomechanics', 'psychology']
List after sort: ['biology', 'Biomechanics', 'Physics', 'psychology']
def myfunction(x):
return x % 10
list1 = [17, 23, 46, 51, 90]
print("List before sort:", list1)
list1.sort(key=myfunction)
print("List after sort:", list1)
Output:
List before sort: [17, 23, 46, 51, 90]
List after sort: [90, 51, 23, 46, 17]
