Sorting is a fundamental operation in data processing and algorithms. Whether you're organizing a list of names, arranging numerical data, or ordering objects by attributes, sorting helps you manage and analyze data efficiently. Today, we're exploring the sorted
function in Python. By the end of this lesson, you will understand how to use the sorted function to sort data in various ways, leveraging its powerful and flexible features.
Let's start with the basics. The sorted
function returns a new list containing all items from the original iterable in ascending order. It doesn't modify the original list but returns a sorted result.
Here's a simple example:
Python1if __name__ == "__main__": 2 numbers = [5, 1, 9, 3, 7] 3 sorted_numbers = sorted(numbers) 4 print("Sorted numbers (ascending):", sorted_numbers) # Output: [1, 3, 5, 7, 9]
In this code, we define a numbers
list and use the sorted
function to sort it in ascending order.
To sort in descending order, set the reverse
parameter to True
in the sorted
function:
Python1if __name__ == "__main__": 2 numbers = [5, 1, 9, 3, 7] 3 sorted_numbers_desc = sorted(numbers, reverse=True) 4 print("Sorted numbers (descending):", sorted_numbers_desc) # Output: [9, 7, 5, 3, 1]
When dealing with a list of objects, you can sort the objects based on a specific attribute using the key
parameter in sorted
.
Here's how you can sort students by their ages:
Python1class Student: 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 6 def __repr__(self): 7 return f"{self.name} ({self.age})" 8 9if __name__ == "__main__": 10 students = [Student("Alice", 26), Student("Bob", 22), Student("Charlie", 23)] 11 sorted_students = sorted(students, key=lambda student: student.age) 12 print("Students sorted by age:", sorted_students) # Output: [Bob (22), Charlie (23), Alice (26)]
In this example, the key
parameter is set to a lambda function that extracts the age
attribute from each Student
object. The sorted
function uses the values returned by this lambda function to sort the list of students.
To handle ties when sorting by one attribute, return a tuple from the key
function where the first element is the primary sort key and subsequent elements are tie-breakers. For example, sort students by age and name:
Python1if __name__ == "__main__": 2 class Student: 3 def __init__(self, name, age): 4 self.name = name 5 self.age = age 6 7 def __repr__(self): 8 return f"{self.name} ({self.age})" 9 10 students = [Student("Alice", 22), Student("Bob", 22), Student("Charlie", 23)] 11 sorted_students = sorted(students, key=lambda student: (student.age, student.name)) 12 print("Students sorted by age and name:", sorted_students) # Output: [Alice (22), Bob (22), Charlie (23)]
In this lesson, we've explored the versatile sorted
function in Python. You now understand how to:
The sorted
function is powerful and flexible, making it essential in any Python programmer's toolkit. Next, you will get hands-on practice to solidify your understanding and improve your coding skills.