Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
111 views
in Python by (176k points)
How do you customize the sort function in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

In Python, you can customize the sort function by defining a key function that takes an element from the list and returns a value to be used for sorting. The key function should return a value that is used to compare elements in the list. The sort() method and the sorted() function take a key argument that is used to specify the custom sorting function.

Here is an example of customizing the sort function to sort a list of dictionaries based on a specific key:

my_list = [    {"name": "Alice", "age": 25},    {"name": "Bob", "age": 20},    {"name": "Charlie", "age": 30},    {"name": "David", "age": 22}]

def sort_by_age(item):
    return item["age"]

my_list.sort(key=sort_by_age)
print(my_list)
 

Output:

[{'name': 'Bob', 'age': 20}, {'name': 'David', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
 

In this example, the sort_by_age() function takes a dictionary item as an argument and returns the value associated with the "age" key. This function is used as the key argument for the sort() method to sort the list of dictionaries based on the "age" value.

You can customize the sorting function based on any criteria you want. For example, you can sort a list of strings based on their length by defining a key function that returns the length of the string:

my_list = ["apple", "banana", "cherry", "date"]
my_list.sort(key=len)
print(my_list)
 

Output:

['date', 'apple', 'cherry', 'banana']
 

In this example, the key function returns the length of each string in the list, and the sort() method uses this function to sort the list of strings based on their length.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 20, 2023 in Python by kvdevika (176k points)
0 votes
2 answers
asked Mar 20, 2023 in Python by kvdevika (176k points)
+1 vote
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...