Loop Control Statements in C
Introduction to HTML
How to use the Github API
The image tag, anchor tag and the button tag
Ordered and Unordered Lists in HTML
The division tag
HTML Forms
Tables in HTML
Introduction to C Programming
Introduction to Python
Varibles and Datatypes in Python
Operators in Python
Typecasting in Python
Input and Output in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Python practice section 1
Lists in Python
Tuple in Python
Higher Order Sort in Python
- Built-in sort functions
- Higher Order Sort
Jump to specific sections
Built-in sort functions
The sort() function modifies the original list. Consider the below code.
student_list=[('Aditi',50),('Vaibhav',68),('Akshay',70)]
# To sort in ascending order
student_list.sort()
print("student_list in ascending order = ",student_list)
# To sort in descending order
student_list.sort(reverse=True)
print("student_list in descending order = ",student_list)
Output
student_list in ascending order = [('Aditi',50),('Akshay',70),('Vaibhav',68)] student_list in descending order = [('Vaibhav',68),('Akshay',70),('Aditi',50)]
The sorted() function returns a new copy of the original list after sorting it.
student_list=[('Aditi',50),('Vaibhav',68),('Akshay',70)]
print("student_list = ",student_list)
print()
sorted_student_list=sorted(student_list)
print("sorted_student_list = ",sorted_student_list)
Output
student_list = [('Aditi',50),('Vaibhav',68),('Akshay',70)] sorted_student_list = [('Aditi',50),('Akshay',70),('Vaibhav',68)]
Higher Order Sort
By default, if we sort an object, it gets sorted based on its first property.
As we can see in the above examples, student_list contains tuples of student
and their marks. On applying the sort function, it gets sorted based on the names
since it is the first property in the tuples. But suppose you want to sort the list
based on the marks rather than names without changing the original list.
The sort function accepts a keyword argument key that accepts a function that provides the property of the object on the basis of which you want to sort. Consider the below code.
The sort function accepts a keyword argument key that accepts a function that provides the property of the object on the basis of which you want to sort. Consider the below code.
# func accepts every item of the student_list i.e. each tuple and returns the marks of each tuple.
def func(student):
return student[1]
student_list=[('Aditi',50),('Vaibhav',68),('Akshay',70)]
student_list.sort(key=func)
print(student_list)
Output
[('Aditi', 50), ('Vaibhav', 68), ('Akshay', 70)]