Sorting in Python with sorted(): The Essential Guide

The sorted() function is a powerhouse in Python, enabling you to arrange collections of data in a specific order. Whether you’re dealing with numbers, strings, or even more complex objects, sorted() provides a flexible and efficient way to bring order to your data. This guide will walk you through the basics of the sorted() function, explore its use with different data types, and demonstrate how to customize sorting behavior.

1. The sorted() Function: Sorting Made Easy

Python’s sorted() function takes an iterable (like a list, tuple, or string) as input and returns a new list containing the same elements in sorted order.

Example: Sorting Numbers

points = [0, -10, 15, -2, 1, 12]
sorted_points = sorted(points)
print(sorted_points)  # Output: [-10, -2, 0, 1, 12, 15] 

Example: Sorting Strings

children = ["Sue", "Jerry", "Linda"]
sorted_children = sorted(children)
print(sorted_children)  # Output: ['Jerry', 'Linda', 'Sue']

2. Customizing Sorting: The key Argument

The key argument allows you to specify a function to be called on each item before comparison. This enables you to sort objects based on specific attributes or criteria.

students = [("Alice", "B", 12), ("Eliza", "A", 16), ("Tae", "C", 15)]
sorted_by_grade = sorted(students, key=lambda student: student[1])
print(sorted_by_grade) 

In this example, we sort a list of student tuples by their grade (the second element in each tuple).

3. Reverse Order: Sorting in Descending Order

Use the reverse=True argument to sort in descending order:

sorted_points_desc = sorted(points, reverse=True)
print(sorted_points_desc) # Output: [15, 12, 1, 0, -2, -10]

4. Sorting Dictionaries: Keys or Values?

You can sort the keys of a dictionary using sorted(my_dict) or the values using sorted(my_dict.values()).

leaderboard = {231: "CKL", 123: "ABC", 432: "JKC"}
sorted_scores = sorted(leaderboard, reverse=True)  # Sort by keys (scores) in descending order
print(sorted_scores) 

Frequently Asked Questions (FAQ)

1. Does the sorted() function modify the original list?

No, it returns a new sorted list, leaving the original list unchanged.

2. Can I sort a list in place (without creating a new list)?

Yes, use the list.sort() method to sort a list in place.

3. How does Python determine the sort order for different data types?

1. Numbers are sorted numerically.
2. Strings are sorted lexicographically (alphabetically).
3. Custom objects require you to define comparison magic methods (e.g., __lt__) to specify the sorting behavior.

4. What’s the difference between the sorted() function and the sort() method?

The sorted() function returns a new sorted list, while the sort() method sorts the list in place and doesn’t return a value.

5. How can I sort a list of lists?

You can use nested sorted() calls or a custom key function that compares the sublists based on the desired criteria.